Question is simple: how do I access variable from a service without passing down that components variable through function itself?
I don't want to pass it through function, because I want to access the variable located in AppComponent
called thingies
from tabs.service
BUT called from sitetree.service
. Function f_in_sitetreeService
is gona be called somewhere at some time, dynamically (in plunker I call it from appcomponent, but in reality it will be from another place).
In other words, I have a service which is calling another service function, which in turn accesses it's components variable.
What I want:
In tabs.service
I commented out 2 lines, which pushes a new thingy, and then logs the array. Commented them out because I don't know how to correctly declare/access that components array there, and that's what I need to know.
Plunker: http://plnkr.co/edit/rFSW1UXz7Gw1rMXlD2Md?p=preview
I'm not sure I understand your question, but I'll try answering...
It sounds like you want TabsService to manipulate a property defined on some component (in your example, the AppComponent). First comment: this is likely not a good approach. Normally services should own application data, not components.
However, if you really need/want to do that, you have to somehow pass a reference to the array to your service, say in ngOnInit in the AppComponent:
ngOnInit() {
this.tabsService.setArrayReference(this.thingies);
}
Then in TabsService:
setArrayReference(ref) { this.thingies = ref; }
Since we're dealing with a JavaScript reference type, both the AppComponent and the TabsService will now both reference the same/one array.
Now you can access and manipulate the array from the AppComponent and the TabsService.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.