angular2 - 从父路由到子路由的传递值

angular2 - Pass value from parent route to child route

我有一个名为 home 的路由,它有三个子路由,文件,邮件和垃圾。在 home 路由组件中,它有一个名为 'user' 的变量。我知道有几种方法可以在突出显示 here 的父组件和子组件之间传递信息,但我应该如何在 parent/child 路由之间传递信息。

{ path: 'home',  component: HomeComponent, children: [
        { path: 'documents',  component: DocumentsComponent },
        { path: 'mail',  component: MailComponent },
        { path: 'trash',  component: TrashComponent },
    ]
},

服务

import { Injectable } from '@angular/core';
@Injectable()
export class HomeService {
  // Mock user, for testing  
  myUser = {name:"John", loggedIn:true};
  // Is Super Admin
  isLogged():boolean {
    if(this.myUser.role == true){
      return true ; 
    }
    return false ; 
  }
}

组件

  constructor(public router: Router, public http: Http, private homeService: HomeService) {

  }

  isLogged(){
    return this.homeService.isLogged(); 
  }

模板

<div class="side-nav fixed" >
    <li style="list-style: none">
        <img alt="avatar" class="circle valign profile-image" height="64" src=
        "../images/avatar.jpg" width="64">
        <div class="right profile-name">
            <!-- Value not changing even with service --> 
            {{myUser.role}} 
        </div>
    </li>

您可以使用通用服务来传递数据,如 Angular Documentation

中所述

基本上,您可以创建一个包含用户对象的服务,该对象可以在您的父路由加载或对父组件执行某些操作后进行更新。

用户服务

   import { Injectable } from '@angular/core';
   import { Subject }    from 'rxjs/Subject';

   @Injectable()
   export class UserService {
     // Observable user 
     user = new Subject<string>();
   }

然后当加载子路由组件时,您可以从服务中检索值。

主页组件

 @Component({
   ... 
 })
 export class HomeComponent{
   ... 
   constructor(private userService:UserService ){}
   someMethod = () =>{
      this.userService.user.next(<pass user object>);
   }
 }

邮件组件

 @Component({
   ... 
 })
 export class HomeComponent{
   ... 
   constructor(private userService:UserService ){
     this.userService.user.subscribe(userChanged);  
   }

   userChanged = (user) => {
     // Do stuff with user
   }
 }

如果您在父级中添加提供程序,服务对象将在子级中成为相同的实例。

查看:- https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array

您可以在点击更改路由时传递数据:-

<a [routerLink]="['/crisis-center', { foo: myVar }]">Crisis Center</a>