组件中的 Angular 服务调用函数 [英] Angular service call function in component
问题描述
所以我知道你可以让两个不相关的组件通过一个服务相互通信,方法是让一个组件在服务中发出一个事件,另一个在服务中订阅它.
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.
我的问题:
服务可以直接调用组件中的函数吗?
Can a service call a function in a component directly?
推荐答案
默认情况下不是.服务是类的实例,仅此而已.
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 {}
通过这种方式,服务 (MyService
) 实例被传递给 MyComponent
,但仅此而已.服务实例不知道MyComponent
.
This way a service (MyService
) instance gets passed to MyComponent
but that is all. The service instance has no knowledge about MyComponent
.
您可能想要的是将 Observable
添加到您的服务并在您的组件中订阅它.
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);
}
}
这样,当 Observable
someObservable
发出另一个值时,服务调用"组件上的方法.
this way the service "calls" a method on the component when the Observable
someObservable
emits another value.
更多详情参见检测嵌套属性的变化用于组件输入
这篇关于组件中的 Angular 服务调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!