Angular2从服务调用组件 [英] Angular2 call a Component from a Service
问题描述
我正在尝试从服务
中调用组件
中的方法。这样做的正确方法是什么?我曾尝试使用 rxjs Subject
创建一个Observable,但我无法触发它。
I am trying to call a Method in my Component
from a a Service
. What is the proper way to do this? I have tried to use rxjs Subject
to create an Observable, but I cannot get it to fire.
import {Subject} from 'rxjs/Subject';
export class MyService {
callComponent = function(value) {
let invokeEvent = new Subject();
invokeEvent.next({some:value})
}
}
和我的组件
export class MyComponent {
constructor(private _myService: MyService) {
this._myService.invokeEvent.subscribe(value => console.log(value))
}
}
推荐答案
以下是plunker: http://plnkr.co/edit/WKSurRJMXo5JZOPrwSP5?p=preview
Here's the plunker: http://plnkr.co/edit/WKSurRJMXo5JZOPrwSP5?p=preview
更改您的服务
import {Subject} from 'rxjs/Subject';
@Injectable()
export class MyService {
invokeEvent:Subject<any> = new Subject();
callComponent(value) {
this.invokeEvent.next({some:value})
}
}
别忘了在你的组件中提供它
Don't forget to provide it in your component
@Component({
selector: 'my-component',
template: `
`,
providers: [MyService]
})
export class MyComponent {
constructor(private _myService: MyService) {
this._myService.invokeEvent.subscribe(value => console.log(value));
setTimeout(()=>{
this._myService.callComponent(1);
},1000);
}
}
此外,如果您希望此服务成为全球服务共享服务;将(提供)它放在你的bootstrap(旧)或ngModule中,这样它将在你的应用程序中共享同一个单例实例。
Also, If you want this service to be a global shared service; put(provide) it in your bootstrap(old) or ngModule so it will share the same singleton instance throughout your app.
这篇关于Angular2从服务调用组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!