2017-03-28 35 views
0

我有包含以下一個父容器:角2 - 從子傳遞(內路由器出口)的數據到父組件

<div id="pageContainer"> 
     <router-outlet></router-outlet> 
</div> 

<div> 
    <div class="title">{{text}}</div> 
</div> 

我也有我打算使用通過從數據的服務子組件(路由器出口內)到父組件:

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

@Injectable() 
export class NotificationsService { 


    emitChange(change: any) { 

     return change; 

    } 

} 

的子組件調用服務方法:

this.notificationsService.emitChange('Data from child'); 

然後父組件受讓人{{文本}}從服務:

constructor(
     private notificationsService: NotificationsService 
    ) { 
     notificationsService.emitChange(
      text => { 
       console.log(text); 
      }); 
    } 

但是,這仍然無法正常工作,任何想法?

+0

父組件中是否有文本屬性? – DeborahK

+0

爲什麼你想在路由器插座內傳遞數據?有沒有特定的原因?如果你的子組件用在你的父組件中,你可以使用一個EventEmitter來傳遞數據。 –

+0

@KerimEmurla因爲我必須在整個應用程序中顯示一個通知框,並且從任何地方都必須傳遞一些數據,這似乎是有意義的。 –

回答

0

使用,但必須這樣做

import { Injectable } from '@angular/core'; 
import { Subject, BehaviorSubject } from "rxjs/Rx"; 

@Injectable() 
export class NotificationsService { 
    emitChange$: Subject<any> = new BehaviorSubject<any>(null); 
    constructor() { } 
    emit(value: any) { 
    this.emitChange$.next(value); 
    } 
    get emitChange(): BehaviorSubject<any> { 
    return (this.emitChange$ as BehaviorSubject<any>); 
    } 
} 

在你的孩子

this.notificationsService.emit('Data from child'); 

在父母

constructor(
    private notificationsService: NotificationsService 
) { 
    notificationsService.emitChange.subscribe(
     text => { 
      console.log(text); 
     }); 
} 

順便說一句,如果你的孩子組件是直接在父組件使用,你可以使用EventEmitter在它們之間進行通信。

+0

謝謝我給出了一個去,但控制檯日誌讀出null –

+0

這是初始值,你是否調用該代碼this.notificationsService.emit('Data from child');' –

+0

是的我試過了ngOnInit()上的子組件 –

相關問題