Reputation: 3040
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);
}
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);
}
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
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
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