In angular 2, is it possible to access the calling component (component that is calling the service) from the service?
Let's say my component is:
@Component({
selector: 'my-component',
templateUrl: 'myTemplate.html',
providers: [Service]
})
export class MyComponent{
constructor(private service:Service) {
service.accessComponent();
}
callMe(){
console.log('hello');
}
}
And my service would be:
@Injectable()
export class Service{
accessComponent(){
var myComponent = ???;
myComponent.callMe();
}
}
this is wrong to call component from service. you shuold call service in component! this is architecture of angular 2. read this
Service:
@Injectable()
export class Service{
accessComponent(){
alert('Hi!')
}
}
Component:
@Component({
selector: 'my-component',
templateUrl: 'myTemplate.html',
providers: [Service]
})
export class MyComponent{
constructor(private service:Service) {
service.accessComponent(); //and you see alert!
}
}
To achieve that, you could create Subject in service and emit next
on it in the service.
Then subscribe to the subject in your component, calling the method once stream will emit the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With