KCarnaille
KCarnaille

Reputation: 1057

Angular2 [routerLink] construction fail

I'm learning angular2 by building a little blog. I use angular-cli with typescript 2.

I've got an issue with a little component. When you are in an article page, I want a "Previous" and "Next" links to acccess other articles.

My paths are made like this: article/:id/:slug

Within my class Component: my code so far (and my issue, below) :

  getUrlParams() {
    this.activatedRoute.params.subscribe( (param) => {
        this.loadPrevArticle(param);
    })
  }

  loadPrevArticle(param){
      let id = Number(param['id']); // Converts the original string to number

      return this.myService.getArticles().subscribe((data) => {
         // some stuffs to get the article object I want, actually working :)
      });
  }

My service looks like this :

getArticles() {
    return this.http.get('my_api_link').map(
        (res: Response) => res.json()
    );
}

I got my datas, the service is working properly but...

MY PROBLEM :

When I call my this.getUrlParams() method in the ngOnInit(), the [routerLink] in my template display an error. The object is not found.

[routerLink]="['/article', nextArticle.id, nextArticle.slug]

But when I move my method into the class constructor, it works. I know this is not a good practice to do this, I'd prefer to move everything in the ngOnInit()

Any ideas how to do this ? I'm a bit lost right now...

SOLUTION :

Adding on the html element:

*ngIf="nextArticle" [routerLink]="['/article', nextArticle.id, nextArticle.slug]"

It will wait for the data before rendering :) Thanks Gunter

Upvotes: 1

Views: 76

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657118

You could add an *ngIf to prevent the routerLink being created before nextArticle is available:

*ngIf="nextArticle" [routerLink]="['/article', nextArticle.id, nextArticle.slug]"

or

[routerLink]="nextArticle ? ['/article', nextArticle.id, nextArticle.slug] : null" 

Upvotes: 1

Related Questions