Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

behavior subject doesnt udate

I’m trying to set my language in the BahaviorSubject using a default value in a LanguageService. My service looks like thi

import {Injectable} from '@angular/core';
import * as globals from '../../../environments/globals';
import {BehaviorSubject} from 'rxjs';

@Injectable()
export class LanguageService {
    languages = globals.languages;

    language = new BehaviorSubject<string>(this.languages.polish.code);

    setLanguage(code: string) {
        console.log(code)
        this.language.next(code);
    }

    getLanguage() {
        return this.language.asObservable();
    }
}

it is provided by the SharedModule which is then imported by every single component I have.
The problem is that using setlangueage I can see the proper code Im setting, but the getLanguage always returns mi the default value. I’ve never had a problem with BehaviorSubject before so I’m not sure what can be the cause.

I’ve implemented

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this.languageSubscription = this.languageService.getLanguage().subscribe((language: string) => {
            console.log(language);
        })

in one of my components to see if it’s ok but… it isn’t. Any clues?

I think the problem is connected with routing, when I changd to AsyncSubject od normal Subject then on changing the screen I got nothing in getLanguage() like it’s never called

>Solution :

remove service from any providers arrays and change decorator to:

@Injectable({providedIn: 'root'})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading