2017-08-27 40 views
0

我有一個日期範圍不同的組件,我想與大家分享當中不同的組件所選擇的日期,而無需在所有組件Angular2將數據傳遞到使用服務

,所以我有architectured我的應用程序這樣

複製代碼
<app-date-range /> //date range component 
<router-outlet></router-outlet> 

我也創建了我在我的應用程序模塊供應商已經增加了一個事件服務

@Injectable() 
export class ReportsEventService { 

public maininputrange = new Subject(); 
constructor() { } 

maininputrangeemit(data:any){ 
    this.maininputrange.next({type:"mainputrange", data:data}); 
} 

} 

在我的日期範圍組件我發出這樣的

constructor(
    private _reportEventService:ReportsEventService 
){ } 

    dateRangeChanged(data){ 
    ...other implementations 
    this._reportEventService.maininputrangeemit(this.mainInput); 
    } 

NOw我想當我訪問另一個組件訪問初始化發射的數據。

mainInput:any; 
    constructor(
     private _reportsEvenService:ReportsEventService 
    ) { 
    _reportsEvenService.maininputrange.subscribe(
     (data)=>{ 
     console.log("receiving values"); //called many times 
     this.mainInput = data; 
     } 
    ) 
    } 

ngOnInit() { 
    console.log("maininput value is"); 
    console.log(this.mainInput); //always undefined 

} 

我在哪裏錯了,是我的實現可能嗎?

+0

使用'BehaviourSubject',而不是'Subject'。我寧願設置REDX(ngrx-store) – Aravind

+0

感謝行爲主題的作品。 –

+0

快樂編碼。 :) :) – Aravind

回答

0

如果你仍然想知道什麼地方出了問題,在這裏。 在你ReportsEventService你只有一個setter方法,你沒有一個getter方法來返回值。

@Injectable() 
 
export class ReportsEventService { 
 

 
    public maininputrange = new Subject(); 
 
    constructor() {} 
 

 
    setmaininputrangeemit(data: any) { 
 
    this.maininputrange.next({ 
 
     type: "mainputrange", 
 
     data: data 
 
    }); 
 
    } 
 

 
    getmaininputrangeemit(): Observalble <any> { 
 
    return this.maininputrange.asObservable; 
 
    } 
 

 
}

mainInput: any; 
 
constructor(
 
    private _reportsEvenService: ReportsEventService 
 
) { 
 
    _reportsEvenService.getmaininputrange.subscribe(
 
    (data) => { 
 
     console.log("receiving values"); //called many times 
 
     this.mainInput = data; 
 
    } 
 
) 
 
} 
 

 
ngOnInit() { 
 
    console.log("maininput value is"); 
 
    console.log(this.mainInput); //always undefined 
 

 
}

相關問題