Angular 2 router resolve server request before opening a component

旧时模样 提交于 2019-12-02 04:32:07

问题


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?

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

回答1:


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



来源:https://stackoverflow.com/questions/34734367/angular-2-router-resolve-server-request-before-opening-a-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!