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?
i found this blog post that answers my question:
http://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html
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 classnot 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:
some.component.html:
hope this answer will help someone,
good luck