Omar
Omar

Reputation: 3040

Angular 6 RxJs: Trying to make an obj as observable to be use in other components

Service

mode: Subject<any> = new Subject<any>();

constructor(public http: HttpClient) {
    this.setMode({ // defaults
        admin: this.admins.includes(localStorage.getItem("email")),
        edit: false,
        dev: false
    });
}

getMode() {
    return this.mode.asObservable();
}

setMode(value) {
    this.mode.next(value);
}

Component

constructor(private bcAuthService: BcAuthService) {}

ngOnInit() {
  this.bcAuthService.getMode().subscribe(mode => {
    console.log('mode: ', mode); // never logs or prints in the template
    this.mode = mode;
  });
}
editToggle(e) {
  this.mode.edit = e.target.checked; // err: cant edit `mode` because it never set.
  this.bcAuthService.mode.next(this.mode);
}

Question

I am trying to set up an Observable to be read and wrote from many components. As seen above; I set up the observable in my service but my component getMode() doesnt work. Any ideas why?

Upvotes: 1

Views: 1491

Answers (2)

cRAN
cRAN

Reputation: 305

editToggle(e) {
this.mode.edit = e.target.checked; // err: cant edit `mode` because it 
// never set.
this.bcAuthService.setMode(e.target.checked);
}

I guess this should work

I did something similar by modifying a fork Component Interaction.

Upvotes: 0

Rub&#233;n Soler
Rub&#233;n Soler

Reputation: 1187

Your architecture is correct, but I think you should use BehaivourSubject instead of Subject

try this:

import { BehaviorSubject } from 'rxjs/BehaviorSubject';

Service

mode: BehaviorSubject<any> = new BehaviorSubject<any>(null);

    constructor(public http: HttpClient) {
        this.setMode({ // defaults
            admin: this.admins.includes(localStorage.getItem("email")),
            edit: false,
            dev: false
        });
    }

    getMode() {
        return this.mode.asObservable();
    }

    setMode(value) {
        this.mode.next(value);
    }

BehaviorSubject vs Subject

What is the difference between Subject and BehaviorSubject?

Upvotes: 4

Related Questions