本文介绍了Angular 2路由器在打开组件之前解析服务器请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a BookDetailComponent component which is mapped for an url /books/:id. Is there any way in angular 2 router to make sure that this component is opened only after the Book with given id is retrieved from server?

我正在寻找类似的功能,例如 ui-router resolveAngular 2 路由器.

I am looking for similar functionality like ui-router resolve in Angular 2 router.

/*** 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());
  }
}

推荐答案

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

Yes, by implementing the OnActivate interface and returning a promise of the object you are waiting to load:

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

这篇关于Angular 2路由器在打开组件之前解析服务器请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 15:20