angular2-将值从父管线传递到子管线

angular2 - Pass value from parent route to child route

本文关键字:angular2-      更新时间:2023-09-26

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

{ 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##链路参数阵列

您可以在更改路线时传递数据,点击如下:-

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