问题
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