簡體   English   中英

如何從另一個組件調用一個組件函數

[英]How to call one component function from another component

嗨,我是Angular的新手,我正嘗試從另一個組件調用一個組件函數,我在閱讀其他類似的問題,但是它們有一個方案,其中的組件是組件或同級組件,並且在html上有聲明,但是我的情況是diff為此,我使用下面的代碼,但它不工作(方法不調用)可以有人幫我嗎

MessageService:

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);
    }

}

ClassA的:

@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');
     }
 }

ClassB的:

@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位置。 您已經在HeaderComponentStoreComponent兩個不同Modules中聲明了MessageService 由於它無法創建兩個單獨的MessageService實例,因此它們無法通信。

固定

您應該在HeaderComponentStoreComponent通用的Module中提供MessageService

如果不確定通用模塊,則可以通過在AppModule提供對其進行AppModule

app.module.ts

providers: [
    MessageService
]

注意:不要忘記從其他Modulesproviders中刪除MessageService

必須將MessageService添加到ClassA和ClassB的父模塊。 比您的代碼能正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM