Can't call function from another component onclick button - Angular 13

126 Views Asked by At

I have a header button that changes a parameter, and need to call a function in another component when that paran changes in the header. I tried two ways using the EventEmitter and a subject to send the click event to the component that has the function I want to call. I leave a console.log in each component and in the service to see the data sent, but in the last component the call happens only in the ngOnInit and the constructor. Where should I place the subscription to get the header button to call my function?

Service.ts

import { Injectable, EventEmitter } from '@angular/core';
import { Observable, Subject, Subscription, BehaviorSubject } from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class Service {

  private subject = new Subject<any>();

  subject$ = this.subject.asObservable();

  sendClickEvent(data) {
    console.log(data)
    this.subject.next(data);
  }
}

HeaderComponent.ts

import { Component, OnInit, EventEmitter} from '@angular/core';
import { Service } from 'app/helpers/service.service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
  constructor(
     public _service : Service
  ){}

  changeParam(param){
    console.log(param, "header")
    this._service.sendClickEvent(param)
  }
}

MainComponent.ts

import { Subscription } from "rxjs";
import { Component, OnInit} from '@angular/core';
import { Service } from 'app/helpers/service.service';

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.scss']
})

export class MainComponent implements OnInit {
  subscription : Subscription;

  constructor(public _service : Service){
     
  }
  ngOnInit() {
    this.subscription = this._service.subject$.subscribe((data: string)=>{
      console.log(data) // nothing appears here on call of function changeParam in header
    })
  }
}
1

There are 1 best solutions below

1
user3258996 On

The name of the service's class is LocationService, not just Service, it looks like you're importing something else in your components.