2017-01-02 20 views
0

我在服務「MySharedService」已在「MyOutputTemp」的值有一個數據。我想在組件加載時將其顯示在組件中。從服務抓取數據,並在加載/組件中顯示它呈現:Angular2

這裏是我的組件:

@Component({ 

    template: `.... 
       <p>{{MyOutputHere}} 
       .....` 

    providers: [MySharedService] 

}) 

export class MyOutputComponent implements OnInit{ 

    MyOutputHere: string; 

    constructor (private _mySharedService: MySharedService){} 

    ngOnInit(){ 
     console.log('Getting value from the service: ' + this._mySharedService.MyOutputTemp); //says undefined 
     this.MyOutputHere = this._mySharedService.MyOutputTemp; 
     console.log('Value in the component: ' +this.MyOutputHere);//says undefined 

    } 
} 

這裏是我的服務:

@Injectable() 
    export class MySharedService{ 

     MyOutputTemp: string; 

     assignOutput(incomingParameter: string){ 

      this.MyOutputTemp = incomingParameter; 
      console.log('Assigned value: ' + this.MyOutputTemp); 
      //the value is successfully assigned and I can get a print 

     } //I am calling it in another component. It is successfully assigning the value. Consider MyOutputTemp has value now. 

    } 

我的嘗試:用ngOnInit(),以獲得從服務的價值,並把它放在「 MyOutputHere」。 發生了什麼:{{MyOutputHere}}顯示沒有值。如果我在控制檯中打印這個值,它會顯示「未定義」。

什麼那麼它在概念錯在這裏? 而且,如何從服務中獲取MyOutputTemp的值並將其顯示在組件中?

+0

你有沒有叫'assignOutput'其中分配一定的參考價值'MyOutputTemp'。你應該先調用函數來設置它。 –

+0

我在另一個組件中調用它。它正在成功分配值。考慮MyOutputTemp有價值。 –

+0

是否在組件內觸發'ngOnInit'事件時查看該值是否已設置? –

回答

1

你應該在服務中MyOutputTemp變量static變量。

例如:

@Injectable() 
export class MySharedService{ 

    static MyOutputTemp: string; 

    assignOutput(incomingParameter: string){ 

     MySharedService.MyOutputTemp = incomingParameter; 

    } 
} 

在組件:

export class MyOutputComponent implements OnInit{ 

    MyOutputHere: string; 

    constructor (private _mySharedService: MySharedService){} 

    ngOnInit(){ 
     console.log('Getting value from the service: ' + MySharedService.MyOutputTemp); 
     this.MyOutputHere = MySharedService.MyOutputTemp; 
     console.log('Value in the component: ' +this.MyOutputHere); 
    } 
} 

這樣做的原因是,對於每一個組件,該服務的新實例被注入。使變量靜態確保它在所有實例中都是相同的。

乾杯!

+0

是的。情況就是如此。現在正在工作。 –

相關問題