Luis Soto
Luis Soto

Reputation: 21

Angular service subscribe seems to be not working

I have created a service in Angular, emmit method is working fine as i can see in console.log and debug, but after this the code is doing nothing more and is not taking other lines already using service.subscribe...is like subscribe is doing nothing.

Sevice Code:

import { Injectable, Output, EventEmitter } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ServicioDeFavoritosService {
  @Output() disparadorDeFavoritos: EventEmitter<any> = new EventEmitter();

  constructor() { }
}

Emmit code:

import { ServicioDeFavoritosService } from './../servicio-de-favoritos.service';
import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-card',
  templateUrl: './card.component.html',
  styleUrls: ['./card.component.css']
})
export class CardComponent implements OnInit {
  @Input() dataEntrante: any;
  public image: string = "";

  constructor(public servicioFavorito: ServicioDeFavoritosService) {

  }

  ngOnInit(): void {
    this.image="https://www.jquery-az.com/html/images/banana.jpg";
    console.log('Entrando data: ', this.dataEntrante);
  }

  agregarFavorito(dataEntranteParam: any) {
    this.servicioFavorito.disparadorDeFavoritos.emit({
      data: this.dataEntrante
    });
    console.log('Emitiendo data: ', this.dataEntrante);
  }

}

Subscribe code

import { Component, OnInit } from '@angular/core';
import { ServicioDeFavoritosService } from '../servicio-de-favoritos.service';

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent implements OnInit {

  public listadeVideos: Array<any> = []

  constructor(public servicioFavorito: ServicioDeFavoritosService) {

  }

  ngOnInit(): void {
    this.servicioFavorito.disparadorDeFavoritos.subscribe(data => {
      this.listadeVideos.push(data);
    });
  }

}

Upvotes: 0

Views: 398

Answers (1)

Andres2142
Andres2142

Reputation: 2897

The @Ouput() decorator is for emitting an event from a child component to a parent component.

For your case, you need a special observable which can be a Subject, with this, you will be able to communicate between components.

Your service:

import { Injectable, Output, EventEmitter } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ServicioDeFavoritosService {
  private yourSubject$ = new Subject();

  emitAValue(value: any) {
    this.yourSubject$.next(value);
  }

  getValueEmitted(): Observable<any> {
    return this.yourSubject$.asObservable();
  }
}

Card component:

 agregarFavorito(dataEntranteParam: any) {
    this.servicioFavorito.emitAValue({ data: this.dataEntrante });
 }

Sidebar Component

 ngOnInit(): void {
    this.servicioFavorito.getValueEmitted().subscribe(
     (yourValue) => console.log(yourValue)
    )
 }

Upvotes: 1

Related Questions