2017-07-03 133 views
0

我正在嘗試創建一個服務來解析數據到不同路由上的不同組件。Angular 2 Setter和Getter

如果我在相同的組件上調用跟隨服務,我會得到我需要的結果,但是如果我嘗試從另一個組件獲得設置結果,則服務返回undefined。

這裏是我的服務: -

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

@Injectable() 
export class TestService { 

    public _test:any; 

    set test(value:any) { 
    this._test = value 
    } 

    get test():any { 
    return this._test; 
    } 
} 

我設置的服務,如: -

this.testService.test = 3; 

,我使用以下收到我的組件的業務數據: -

console.log(this.testService.test) 

如前所述,如果我在同一個組件中進行通信,這個工作絕對沒問題,我有相同的重要ts,提供者和構造函數。

也只需記下組件同級組件

會有人能夠幫助或點我在正確的方向,將是非常讚賞。

如果您需要任何額外的代碼,請讓我知道。

+0

您的註冊服務如何?在組件中?在模塊中?您能否展示顯示您用於註冊該服務的提供程序數組的代碼? – DeborahK

+0

我正在使用以下提供程序在組件中註冊服務:[TestService],在我的構造函數中我有私人testService:TestService,並使用導入{TestService}從'../../../shared/services /test/test.service'; –

+0

@TonyHensler,你確定他們是liblings嗎? [這個笨蛋](https://plnkr.co/edit/ANgduQg230dNWLdAFtlm?p=preview)顯示你不能注入在兄弟組件 –

回答

2

如果要跨父組件的子組件共享服務,則需要在模塊中註冊服務,而不是在組件中註冊服務。當您在組件中註冊服務時,它僅適用於該組件及其子組件。

事情是這樣的:

@NgModule({ 
    declarations: [ 
    AppComponent, 
    ProductListComponent, 
    StarComponent 
    ], 
    imports: [ 
    BrowserModule, 
    FormsModule, 
    HttpModule 
    ], 
    providers: [ TestService ], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { } 
0

嘗試初始化TestService的變種這樣的代碼在你的Component.ts構造函數的內部,如果不確定的變種是「TestService的」 THA可以工作。

constructor (private testService : TestService){ 
     //at this time testService its already initialized. 
    console.log(this.testService.test); 
}