Reputation: 537
I have a data in my service 'MySharedService' that has a value in 'MyOutputTemp'. I want to show it in a component when the component loads.
Here is my component:
@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
}
}
Here is my service:
@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.
}
What I tried: using ngOnInit() to get the value from the service, and put it in the 'MyOutputHere'. What happens: {{MyOutputHere}} shows no value. If I print the value in the console it says "undefined".
What It conceptually wrong here? And, How can I get the value of MyOutputTemp from the service and show it in the component?
Upvotes: 0
Views: 550
Reputation: 735
You should make the MyOutputTemp
variable in the service a static
variable.
for example:
@Injectable()
export class MySharedService{
static MyOutputTemp: string;
assignOutput(incomingParameter: string){
MySharedService.MyOutputTemp = incomingParameter;
}
}
in the component:
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);
}
}
The reason for this is that for every component, a new instance of the service is injected. Making the varible static ensures it is the same across all instances.
Cheers!
Upvotes: 1