问题
So I know you can have two unrelated components communicate with each other via a service by having one component emit an event in the service and the other subscribe to it in the service.
My question:
Can a service call a function in a component directly?
回答1:
Not by default. A service is an instance of a class, nothing more.
@Injectable()
class MyService {
}
@Component({
selector: 'my-component',
...
)}
class MyComponent {
constructor(private myService:MyService) {}
}
@NgModule({
providers: [MyService],
...
})
export class AppModule {}
This way a service (MyService) instance gets passed to MyComponent but that is all. The service instance has no knowledge about MyComponent.
What you probably want is to add an Observable to your service and subscribe to it in your component.
@Component({
selector: 'my-component',
...
)}
class MyComponent {
constructor(myService:MyService) {
myService.someObservable.subscribe(value => doSomething(value));
}
doSomething(value) {
console.debug(value);
}
}
this way the service "calls" a method on the component when the Observable someObservable emits another value.
For more details see detect change of nested property for component input
回答2:
The answer above is correct except that you don't bootstrap your service, you will add your service in your providers array in the app.module.
@NgModule({
declarations: [MyComponent],
imports: [],
providers: [MyService],
bootstrap: [AppComponent]
})
Then you inject your service inside of the component
import { Component } from '@angular/core'
import { MyService } from './path/to/my.service'
...
export class MyComponent {
constructor(private myService:MyService){}
}
来源:https://stackoverflow.com/questions/36309837/angular-service-call-function-in-component