Home > Blockchain >  behavior subject doesnt udate
behavior subject doesnt udate

Time:11-10

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

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

CodePudding user response:

remove service from any providers arrays and change decorator to:

@Injectable({providedIn: 'root'})
  • Related