Sunday, 16 April 2017

Angular 4.x component property always null when routing to it

I have the following component:

import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params }   from '@angular/router';
import 'rxjs/add/operator/switchMap';

import { ArticleStore } from '../../state/ArticleStore';
import { Article } from '../../models/article';

@Component({
  selector: 'app-article-detail',
  templateUrl: './article-detail.component.html',
  styleUrls: ['./article-detail.component.css']
})
export class ArticleDetailComponent implements OnInit {

  private article: Article;

  constructor( private route: ActivatedRoute, private articleStore: ArticleStore ) { }

  ngOnInit(): void {
    this.route
        .queryParamMap
        .map((paramMap => paramMap.get('id') || 'None'))
        .switchMap((id: string) => this.articleStore.getArticle(id))
        .subscribe((article: Article) => {
            this.article = new Article(article);
            console.log(this.article) // <--returns full-filled object
        });

        console.log(this.article) // <-- undefined object
    }
}

Inside the subscribe function, I get the proper object (this.article) and is what I expect. If I move down to after the this.route, it doesn't work. Should be straight forward to get the value assigned.

The whole project is here => https://github.com/flamusdiu/micro-blog



via flamusdiu

No comments:

Post a Comment