Reputation: 771
i am working on an angular2 app.
i want to use with a parameter that i get in a promise.
i keep getting this error:
EXCEPTION: Uncaught (in promise): Error: Error in http://localhost:5000/js/angular-client/app/components/some/some.component.html:0:7 caused by: c is null normalizeCommands/_loop_1@http://localhost:5000/js/angular-client/node_modules/@angular/router/bundles/router.umd.js:2384:15 normalizeCommands@http://localhost:5000/js/angular-client/node_modules/@angular/router/bundles/router.umd.js:2427:11 createUrlTree@http://localhost:5000/js/angular-client/node_modules/@angular/router/bundles/router.umd.js:2284:49 Routerhttp://localhost:5000/js/angular-client/node_modules/@angular/router/bundles/router.umd.js:3486:18 RouterLinkWithHrefhttp://localhost:5000/js/angular-client/node_modules/@angular/router/bundles/router.umd.js:4577:22 RouterLinkWithHrefhttp://localhost:5000/js/angular-client/node_modules/@angular/router/bundles/router.umd.js:4570:11 RouterLinkWithHref
this is my code:
some.component.ts:
someAnswer: SomeAnswer;
ngOnInit(): void {
this.sub = this.route.params.subscribe(params => {
this.getPromise(+params['id']);
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
getPromise(id: number): Promise<SomeAnswer> {
return this.http.get('/api/'+id+'')
.toPromise()
.then(response => this.someAnswer = response.json() as SomeAnswer)
.catch(this.handleError);
}
some.component.html:
<h2><a [routerLink]="['/url', someAnswer?.id]">banana</a></h2>
so my question is - how do i use [routerLink] with a parameter that i get from a promise?
Upvotes: 2
Views: 1536
Reputation: 771
i found this blog post that answers my question:
http://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html
The Safe Navigation Operator ensures that Angular won’t throw any errors when we’re trying to read from an object that is null or undefined ... ... ... adding Safe Navigation Operators everywhere can be quite tiring as well. In addition to that, some constructs don’t support that operator, like NgModel and RouterLink directives
so according to this post, routerLink does not support getting null parameters, and the parameter i'm passing (someAnswer?.id) is using the Safe Navigation Operators, and as it is received in a promise - when the page loads it is null.
there are 2 solutions to deal with that:
resolve the data before loading the component
instead of routerLink from the template - use this.router.navigate()
from the component class
not being fond of forcing my async code to become sync, i decided to pass on the resolve option and chose the 2nd solution, this is how it looks:
some.component.ts:
goToPage(id:number) {
this.router.navigate(['/url', id]);
}
some.component.html:
<a (click)="goToPage(someAnswer?.id)">banana</a>
hope this answer will help someone,
good luck
Upvotes: 2