Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BehaviorSubject not working Angular 5

I cant seem to figure out what the issue is,

I have a service that has a behavior subject like so...

popupSource = new BehaviorSubject<any>('');

popup(component) {
   this.popupSource.next(component);
}

then In my header component

popupClick() {
    this._service.popup('example');    
}

then in my header.html

<button (click)="popupClick()"></button>

then In my app component

ngOnInit() {
    this._service.popupSource.subscribe((result) => {
       console.log(result);
    })
}

so whats happening is the click is firing the this._service.popup('example'); but its never hitting the subscription...

I've put breakpoints on each function and It succesfully reaches this.popupSource.next(component) but then nothing?? Every Time I click the button I should be getting the console log.

Im not sure what Im doing wrong... Ive left out code for brevity sake so please let me know if you need more information

EDIT

Ive also tried doing

private popupSource = new BehaviorSubject<any>('');

getPopup = this.popupSource.asObservable();

popup(component) {
   this.popupSource.next(component);
}

and the in my app component listend to the getPopup instead

ngOnInit() {
    this._service.getPopup.subscribe((result) => {
       console.log(result);
    })
}

and that's not working either, I cant figure out what the problem is...

Thanks

like image 582
Smokey Dawson Avatar asked Dec 02 '22 11:12

Smokey Dawson


1 Answers

Your issue here is that you provide your service in two different modules, that end up with two instances of your service. The simplest way if you are using Angular v6 is to use the providedIn flag in your service:

import { Injectable } from '@angular/core';

@Injectable({providedIn: 'root'})
class myService {}

With this way you don't need to provide your service in the providers array of any module, it will be automatically provided in the root injector.

Documentation about this can be found here : Angular providers.

If your are using Angular v5 you should only provide your service in your AppModule.

like image 196
GeoAstronaute Avatar answered Dec 22 '22 12:12

GeoAstronaute