组件中的角度服务调用功能 [英] 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.
有关更多详细信息,请参见检测嵌套属性的更改用于组件输入
For more details see detect change of nested property for component input
这篇关于组件中的角度服务调用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!