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

Activating components

At this point, we have a router state. The router can now activate this state by instantiating all the needed components, and placing them into appropriate router outlets.

To understand how it works, let's take a look at how we use router outlets in a component template.

The root component of the application has two outlets: primary and popup.

@Component({
  template: `
    ...
    <router-outlet></router-outlet>
 
    ...
    <router-outlet name="popup"></router-outlet>
  `
})
class MailAppCmp {
}

Other components, such as ConversationCmp, have only one:

@Component({
  template: `
    ...
    <router-outlet></router-outlet>
    ...
  `
})
class ConversationCmp {
}

Other components, such as ConversationCmp, have only one:

@Component({
  template: `
    ...
    <router-outlet></router-outlet>
    ...
  `
})
class ConversationCmp {
}

Now imagine we are navigating to /inbox/33/messages/44(popup:compose).

That's what the router will do. First, it will instantiate ConversationCmp and place it into the primary outlet of the root component. Then, it will place a new instance of ComposeCmp into the 'popup' outlet. Finally, it will instantiate a new instance of MessageCmp and place it in the primary outlet of the just created conversation component.

Using parameters

Often components rely on parameters or resolved data. For instance, the conversation component probably need to access the conversation object. We can get the parameters and the data by injecting ActivatedRoute.

@Component({...})
class ConversationCmp {
  conversation: Observable<Conversation>;
  id: Observable<string>;

  constructor(r: ActivatedRoute) {
    // r.data is an observable
    this.conversation = r.data.map(d => d.conversation);

    // r.params is an observable
    this.id = r.params.map(p => p.id);
  }
}

If we navigate from inbox/33/messages/44(popup:compose) to /inbox/34/messages/45(popup:compose), the data observable will emit a new map with the new object, and the conversation component will display the information about Conversation 34.

As you can see the router exposes parameters and data as observables, which is convenient most of the time, but not always. Sometimes what we want is a snapshot of the state that we can examine at once.

@Component({...})
class ConversationCmp {
  conversation: Conversation;
  constructor(r: ActivatedRoute) {
    const s: ActivatedRouteSnapshot = r.snapshot;
    this.conversation = s.data['conversation']; // Conversation
  }
}
主站蜘蛛池模板: 梁山县| 新巴尔虎左旗| 东平县| 山阳县| 潞城市| 灵寿县| 宁武县| 平山县| 司法| 二连浩特市| 依安县| 收藏| 思茅市| 高平市| 岗巴县| 鹰潭市| 柳江县| 南昌县| 宁武县| 万安县| 赤水市| 铜山县| 陆丰市| 邹城市| 饶阳县| 柳江县| 阿拉尔市| 泰宁县| 德庆县| 福贡县| 普兰店市| 陆丰市| 青州市| 山东省| 弥渡县| 凯里市| 金堂县| 女性| 同德县| 东乡族自治县| 正安县|