簡體   English   中英

angular2 - 將值從父路由傳遞到子路由

[英]angular2 - Pass value from parent route to child route

我有一條名為 home 的路由,它包含三個子路由、文檔、郵件和垃圾。 在 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 文檔中所述

基本上,您可以創建一個具有用戶對象的服務,一旦您的父路由被加載或對父組件執行某些操作,就可以更新該服務。

用戶服務

   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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM