[英]How to call one component function from another component
嗨,我是Angular的新手,我正嘗試從另一個組件調用一個組件函數,我在閱讀其他類似的問題,但是它們有一個方案,其中的組件是子組件或同級組件,並且在html上有聲明,但是我的情況是diff為此,我使用下面的代碼,但它不工作(方法不調用)可以有人幫我嗎
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MessageService {
private _listners = new Subject<any>();
listen(): Observable<any> {
return this._listners.asObservable();
}
filter(filterBy: string) {
this._listners.next(filterBy);
}
}
@Component({
selector: 'header',
templateUrl: `
<section class="container">
<button (click)="clickFilter()">Open filter</button>
</section>
`
})
export class HeaderComponent {
constructor(private _messageService: MessageService){}
clickFilter():void {
this._messageService.filter('Register click');
}
}
@Component({
selector: 'store',
template: `<article class="card">
Test
</article>`
})
export class StoreComponent {
constructor(private _messageService: MessageService){
this._messageService.listen().subscribe((m:any) => {
console.log(m);
this.onFilterClick(m);
})
}
onFilterClick(event) {
console.log('Fire onFilterClick: ', event);
}
}
您的實現看起來不錯。 唯一的問題是提供MessageService
位置。 您已經在HeaderComponent
和StoreComponent
兩個不同Modules
中聲明了MessageService
。 由於它無法創建兩個單獨的MessageService
實例,因此它們無法通信。
您應該在HeaderComponent
和StoreComponent
通用的Module中提供MessageService
。
如果不確定通用模塊,則可以通過在AppModule
提供對其進行AppModule
。
app.module.ts
providers: [
MessageService
]
注意:不要忘記從其他Modules
的providers
中刪除MessageService
。
必須將MessageService添加到ClassA和ClassB的父模塊。 比您的代碼能正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.