[英]Access component from service
在 angular 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();
}
}
從服務中調用組件是錯誤的。 你應該在組件中調用服務! 這是 angular 2 的架構。閱讀此內容
服務:
@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!
}
}
要實現這一點,您可以在服務中創建主題並在服務中發出next
主題。
然后訂閱組件中的主題,一旦流將發出值,就調用該方法。
首先,你不應該使用addEventListener
,因為要處理點擊,angular2 有它自己的方法 - <div (click)="calledFunc()"></div>
。 這是在 angular2 中添加點擊事件的慣用方式。 (根據評論討論)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.