2017-05-19 46 views
2

我有一個名爲HomeService的服務,並在該服務中設置並獲取一些正在工作的數據。這是我的服務的代碼。觀察角2服務功能的變化

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

@Injectable() 
export class HomeService { 

name:string; 

constructor() { } 

setParams(val) { 
     this.name = val; 
} 
getParams() { 
    return this.name; 
} 

} 

我在成分A設置PARAMS和得到它在組分B。我想要的是繼續觀看getParams()更改第二個組件。 我收到組件A中的參數值,其中我設置了它,但我無法在組件B中獲得這些值。意味着在組件B其不注意變化。

+0

我已經添加了一個答案來實現您的需要。請看看它。你必須使用observable來獲得這個工作,所以它訂閱param,並且每當做出更改時,它都會更新組件 –

回答

6

要跟蹤名稱屬性的更改,您必須使用observables。 更改您的服務如下。

主頁服務:

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

@Injectable() 
export class HomeService { 

    private nameSource = new Subject<any>(); 

    name$ = this.nameSource.asObservable(); 

    setParams(val) { 
     this.nameSource.next(val); 
    } 

} 

在要改變名稱的成分B,它始終保持訂閱了服務的名稱。因此,無論何時在服務中更改名稱(當您爲組件A設置名稱時),您都可以跟蹤更改,並且組件B將得到更新。

以componentB:

import { Component, OnInit, OnDestroy} from '@angular/core'; 
import 'rxjs/add/operator/takeWhile'; 
import { HomeService } from '[add path of home service here]'; 

export class ComponentBComponent implements OnInit, OnDestroy{ 

    private alive: boolean = true; 
    private name: string; 

    constructor(
     private homeService: HomeService; 
    ) { 
     homeService.name$.takeWhile(() => this.alive).subscribe(
      name=> { 
       this.name = name; 
     }); 

    } 

    ngOnInit() { 
     // Whatever to happen OnInit 
    } 

    ngOnDestroy() { 
     this.alive = false; 
    } 

} 

請注意takeWhile()alive用於prevent memory leaks.

無論從任何地方你的名字設置爲主頁服務,

this.homeService.setParams(name); 

這解決方案應該爲你工作。

+0

中的值,謝謝它爲我工作。只需要詳細研究更多關於觀察值的內容。 –

+0

@AhmerKhan所以,這是組件交互。通過這個將幫助你決定哪種技術可以用於不同的場景。快樂的編碼。 https://angular.io/docs/ts/latest/cookbook/component-communication.html –

1

考慮使用基於訂閱的服務對其進行重新邏輯。在組件中,您必須訂閱基於源的observable變量,並且無論何時在源上調用next方法,observable都會觸發,訂閱此可觀察值的組件將收到新的/更新的值,並在subscribe回調中定義您將用這個價值來做。欲瞭解更多信息,請點擊這裏article