我正在开发一个 angular2 应用程序。
我想与我在 promise 中获得的参数一起使用。
我不断收到此错误:
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
这是我的代码:
一些.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>
所以我的问题是 - 我如何将 [routerLink] 与我从 Promise 获得的参数一起使用?
最佳答案
我发现这篇博文回答了我的问题:
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
所以根据这篇文章,routerLink不支持获取空参数,并且我传递的参数(someAnswer?.id)正在使用安全导航运算符,并且因为它是在 promise 中接收的 - 当页面加载时它为空。
有两种解决方案可以解决这个问题:
加载组件之前解析数据
代替模板中的 routerLink - 使用组件类中的
this.router.navigate()
不喜欢强制我的异步代码变为同步,我决定传递解析选项并选择第二个解决方案,这就是它的样子:
一些.component.ts:
goToPage(id:number) {
this.router.navigate(['/url', id]);
}
some.component.html:
<a (click)="goToPage(someAnswer?.id)">banana</a>
希望这个答案能帮助别人,
祝你好运
关于angular - 将 routerLink 与来自 angular2 中的 Promise 的参数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41186724/