2

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());
  }
}
Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
TheKojuEffect
  • 20,103
  • 19
  • 89
  • 125

1 Answers1

5

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

Langley
  • 5,326
  • 2
  • 26
  • 42
  • Thanks. Is there any way we can resolve for `Observable`? – TheKojuEffect Jan 12 '16 at 02:10
  • The documentation doesn't say anything about that but you can test it, or you can call the .toPromise() method of the observable. – Langley Jan 12 '16 at 02:11
  • Hey, do you know if the resolved value can be injected into the component? – TheKojuEffect Jan 12 '16 at 02:15
  • you don't have to inject it, by implementing that method inside the component you are already inside the component, just set the resolved value to a component's property. – Langley Jan 12 '16 at 02:16
  • "If you want to prevent the route from being rendered until the promise is settled you need to use the CanActivate decorator." - brandonroberts https://github.com/angular/angular/issues/6611 – shannon May 03 '16 at 16:20
  • The related information on the otherwise-usually-accurate Auth0 site is not correct: https://auth0.com/blog/2016/01/25/angular-2-series-part-4-component-router-in-depth/ – shannon May 05 '16 at 14:30