在角度2中,是否可以从服务访问调用组件(调用服务的组件)?
让我们说我的组件是:
@Component({
selector: 'my-component',
templateUrl: 'myTemplate.html',
providers: [Service]
})
export class MyComponent{
constructor(private service:Service) {
service.accessComponent();
}
callMe(){
console.log('hello');
}
}
我的服务是:
@Injectable()
export class Service{
accessComponent(){
var myComponent = ???;
myComponent.callMe();
}
}
答案 0 :(得分:1)
首先,你不应该使用addEventListener
,因为要处理点击,angular2有自己的方式来做到这一点 - <div (click)="calledFunc()"></div>
。这是在angular2中添加click事件的惯用方法。 (根据评论讨论)
答案 1 :(得分:0)
从服务中调用组件是错误的。你在组件中呼叫服务!这是角度为2. read this
的架构服务:
@Injectable()
export class Service{
accessComponent(){
alert('Hi!')
}
}
组件:
@Component({
selector: 'my-component',
templateUrl: 'myTemplate.html',
providers: [Service]
})
export class MyComponent{
constructor(private service:Service) {
service.accessComponent(); //and you see alert!
}
}
答案 2 :(得分:0)
要实现此目的,您可以在服务中创建主题,并在服务中对其发出next
。
然后订阅组件中的主题,一旦流将发出该值,则调用该方法。