【问题标题】:Angular 2 router resolve server request before opening a componentAngular 2路由器在打开组件之前解析服务器请求
【发布时间】:2016-04-16 12:28:00
【问题描述】:

我有一个 BookDetailComponent 组件,它映射到一个 url /books/:id。 angular 2 路由器中是否有任何方法可以确保仅在从服务器检索到具有给定idBook 后才打开此组件?

我正在 Angular 2 路由器中寻找类似 @​​987654321@ 的功能。

/*** BookComponent ***/
@RouteConfig([
  {path: "/books/:id", component: BookDetailComponent, as: "BookDetail"},
])

export class BookComponent {
}


/*** BookDetailComponent ***/
export class BookDetailComponent {

  book:Book;

  constructor(private bookService:BookService,
              private routeParams:RouteParams) {
  }


  ngOnInit() {
    let id = this.routeParams.get("id");
    this.bookService.getBook(parseInt(id))
      .subscribe(book => this.book = book.json());
  }
}

【问题讨论】:

    标签: angular angular-ui-router angular2-routing


    【解决方案1】:

    是的,通过实现OnActivate 接口并返回您等待加载的对象的承诺:

    https://angular.io/docs/js/latest/api/router/OnActivate-interface.html

    【讨论】:

    • 谢谢。有什么方法可以解决Observable
    • 文档没有说明,但是你可以测试它,或者你可以调用 observable 的 .toPromise() 方法。
    • 你好,不知道解析后的值能不能注入到组件中?
    • 您不必注入它,通过在组件内实现该方法您已经在组件内,只需将解析的值设置为组件的属性。
    • "如果你想阻止在 promise 完成之前渲染路由,你需要使用 CanActivate 装饰器。" - 布兰登罗伯茨github.com/angular/angular/issues/6611
    猜你喜欢
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 2017-03-02
    相关资源
    最近更新 更多