1

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?

Omar
  • 2,726
  • 2
  • 32
  • 65

2 Answers2

4

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?

Rubén Soler
  • 1,147
  • 8
  • 23
  • `mode: BehaviorSubject = new BehaviorSubject();` gets an error `Expected 1 arguments, but got 0.` – Omar Jun 21 '18 at 18:44
  • 1
    sorry, the constructor requires an argument but you can pass null, it is fixed in my answer now – Rubén Soler Jun 21 '18 at 18:45
  • this works. I dont know why though. Would be nice to see an explanation for when to use `Subject` and `BehaviorSubject`... Either way thank you! – Omar Jun 21 '18 at 18:48
  • you can read more about this here: https://stackoverflow.com/questions/43348463/what-is-the-difference-between-subject-and-behaviorsubject – Rubén Soler Jun 21 '18 at 18:50
  • The summary is: `Subject` only notify the subscribers and `BehaviorSubject` notify and send the value – Rubén Soler Jun 21 '18 at 18:53
0
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.

cRAN
  • 195
  • 1
  • 2
  • 16