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

  • Angular Router
  • Victor Savkin
  • 178字
  • 2021-07-09 19:20:31

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');
  }
}
主站蜘蛛池模板: 岗巴县| 云梦县| 青田县| 建始县| 连平县| 额尔古纳市| 札达县| 灵川县| 沾益县| 吉木乃县| 平塘县| 东平县| 绥芬河市| 邳州市| 荃湾区| 罗甸县| 闵行区| 太保市| 林州市| 大田县| 吴桥县| 沁阳市| 德钦县| 永济市| 南召县| 昌江| 金山区| 蕲春县| 邻水| 耒阳市| 平罗县| 阳泉市| 长沙县| 天峨县| 喀什市| 霍州市| 含山县| 宁波市| 清丰县| 呈贡县| 澄城县|