AbhiRam
AbhiRam

Reputation: 2061

How to call one component function from another component

I am new to Angular and I am trying to call one component function from another component and I was reading other similar questions but they have a scenario where the components are child or sibling components with the declaration on the html, but my scenario is different.

For this I used below code but it's not working: method not calling.

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

Upvotes: 0

Views: 1500

Answers (2)

Serkan KONAKCI
Serkan KONAKCI

Reputation: 51

MessageService must be added to parent module of ClassA and ClassB. Than your code works fine.

Upvotes: 0

Sunil
Sunil

Reputation: 11241

Issue

Your implementation is looking fine. The only issue with is where the MessageService is provided. You had declared MessageService in two different Modules of HeaderComponent and StoreComponent. Due to which its creating two separate instance of MessageService as a result they are not able to communicate.

Fix

You should provide the MessageService in Module which is common to HeaderComponent and StoreComponent.

If you are not sure about the common Module then you can test it by providing in AppModule.

app.module.ts

providers: [
    MessageService
]

Note : Do not forget to remove MessageService from the providers of other Modules.

Upvotes: 1

Related Questions