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

我有一条叫做 home 的路由,它有三个子路由,documents,mail 和垃圾箱.在主路由组件中,它有一个名为用户"的变量.我知道有几种方法可以在父组件和子组件之间传递信息,突出显示 here,但我想如何在父/子路由之间传递信息.

I have a route called home and it has three child routes, documents, mail and trash. In the home route component it has a variable called 'user'. I know there are a few ways of passing info between parent and child components highlighted here, but how am I suppose to pass info between parent/child routes.

{ 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 文档

You may use a common service to pass data like explained in the Angular Documentation

基本上,您可以创建一个具有用户对象的服务,一旦您的父路由被加载或对父组件进行一些操作,就可以更新该用户对象.

Basically you may create a Service which will have a user object, which can be updated once your parent route gets loaded or with some action on parent component.

用户服务

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

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

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

And then when the child route component gets loaded you may retrieve the value from the Service.

主页组件

 @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
   }
 }

如果您在父级中添加提供者,则服务对象在子级中将是相同的实例.

Service object will be same instance in child if you add the provider in the parent.

相关文章