【问题标题】:use routerLink with parameter that is coming from promise in angular2将 routerLink 与来自 angular2 中的 promise 的参数一起使用
【发布时间】:2017-05-02 09:18:20
【问题描述】:

我正在开发一个 angular2 应用程序。

我想与我在承诺中得到的参数一起使用。

我不断收到此错误:

异常:未捕获(承诺中):错误:http://localhost:5000/js/angular-client/app/components/some/some.component.html:0:7 中的错误由以下原因引起:c 为空 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 路由器http://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

这是我的代码:

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);
}

一些.component.html:

<h2><a [routerLink]="['/url', someAnswer?.id]">banana</a></h2>

所以我的问题是 - 如何将 [routerLink] 与我从承诺中获得的参数一起使用?

【问题讨论】:

    标签: angular angular2-routing angular2-template


    【解决方案1】:

    我发现这篇博文回答了我的问题:

    http://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html

    安全导航运算符确保 Angular 在我们尝试读取空或未定义对象时不会抛出任何错误 ………… 在任何地方添加安全导航操作员也会很累人。除此之外,一些构造不支持该运算符,例如 NgModel 和 RouterLink 指令

    所以根据这篇文章,routerLink 不支持获取空参数,并且我传递的参数 (someAnswer?.id) 正在使用安全导航运算符,并且在承诺中收到 - 当页面加载时它是空的。

    有两种解决方案:

    1. 在加载组件之前解析数据

    2. 而不是模板中的 routerLink - 使用组件类中的this.router.navigate()

    不喜欢强制我的异步代码同步,我决定传递解决选项并选择第二个解决方案,这就是它的外观:

    some.component.ts:

    goToPage(id:number) {
        this.router.navigate(['/url', id]);
    }
    

    一些.component.html:

    <a (click)="goToPage(someAnswer?.id)">banana</a>
    

    希望这个答案对某人有所帮助,

    祝你好运

    【讨论】:

    • 为了使用 this.router.navigate,首先需要导入路由器:import { Router } from '@angular/router'; ...并且还要将其注入到构造函数中:constructor(private router: Router)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多