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

  • 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');
  }
}
主站蜘蛛池模板: 迁安市| 中宁县| 黑龙江省| 山东省| 天全县| 西和县| 台南县| 乌鲁木齐县| 德保县| 汉中市| 玛沁县| 会泽县| 平顶山市| 湘阴县| 云梦县| 肥东县| 隆化县| 铜川市| 伊金霍洛旗| 滦南县| 高唐县| 工布江达县| 儋州市| 西吉县| 阳泉市| 营口市| 湘潭县| 崇明县| 泽州县| 濉溪县| 辽宁省| 寿阳县| 建阳市| 同江市| 聂拉木县| 西华县| 观塘区| 云霄县| 镇安县| 京山县| 和平县|