打开一个组件之前,角2路由器解析服务器的请求 [英] Angular 2 router resolve server request before opening a component

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

问题描述

我有被映射为网址 /书籍/ A BookDetailComponent 组件:ID 。是否有角2路由器任何方式,以确保此组件只有在图书给定 ID 打开从服务器检索?

我要寻找像 UI路由器决心类似的功能角2路由器。

  / *** *** BookComponent /
@RouteConfig([
  {路径:/书/:ID,成分:BookDetailComponent,如:BookDetail},
])出口类BookComponent {
}
/ *** *** BookDetailComponent /
出口类BookDetailComponent {  书:书;  构造函数(私人bookService的:bookService的,
              私人routeParams:RouteParams){
  }
  ngOnInit(){
    让ID = this.routeParams.get(ID);
    this.bookService.getBook(parseInt函数(ID))
      .subscribe(书=> this.book = book.json());
  }
}


解决方案

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

https://angular.io/docs/js/最新/ API /路由器/ OnActivate-interface.html

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

解决方案

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆