官术网_书友最值得收藏!

Resolving data

After the router has run the guards, it will resolve the data. To see how it works, let's tweak our configuration from above:

[
  {
    path: ':folder',
    children: [
      {
        path: '',
        component: ConversationsCmp,
        resolve: {
          conversations: ConversationsResolver
        }
      }
    ]
  }
]

Where ConversationsResolver is defined as follows:

@Injectable()
class ConversationsResolver implements Resolve<any> {
  constructor(private repo: ConversationsRepo, private currentUser: User) {}

  resolve(route: ActivatedRouteSnapshot, state: RouteStateSnapshot):
      Promise<Conversation[]> {
    return this.repo.fetchAll(route.params['folder'], this.currentUser);
  }
}

Finally, we need to register ConversationsResolver when bootstrapping our application:

@NgModule({
  //...
  providers: [ConversationsResolver],
  bootstrap: [MailAppCmp]
})
class MailModule {
}

platformBrowserDynamic().bootstrapModule(MailModule);

Now when navigating to /inbox, the router will create a router state, with an activated route for the conversations component. That route will have the folder parameter set to inbox. Using this parameter with the current user, we can fetch all the inbox conversations for that user.

We can access the resolved data by injecting the activated route object into the conversations component:

@Component({
  template: `
    <conversation *ngFor="let c of conversations | async"></conversation>
  `
})
class ConversationsCmp {
  conversations: Observable<Conversation[]>;
  constructor(route: ActivatedRoute) {
    this.conversations = route.data.pluck('conversations');
  }
}
主站蜘蛛池模板: 巍山| 昔阳县| 榕江县| 临安市| 双鸭山市| 古丈县| 丰县| 朔州市| 台中县| 六盘水市| 炉霍县| 巴南区| 六枝特区| 宿松县| 赤城县| 沅陵县| 松溪县| 张家口市| 东台市| 巴林右旗| 防城港市| 凤城市| 长汀县| 连平县| 正镶白旗| 县级市| 泰顺县| 商南县| 松溪县| 祁东县| 峨眉山市| 沙河市| 常熟市| 黎川县| 亚东县| 武邑县| 木里| 黑水县| 玉溪市| 陇川县| 林芝县|