Angular 6 RxJs:试图使一个 obj 可以在其他组件中使用

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

服务

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);
}

问题

我正在尝试设置一个可从多个组件读取和写入的 Observable。如上所示;我在我的服务中设置了 observable,但我的组件 getMode() 不工作。有什么想法吗?

您的架构是正确的,但我认为您应该使用 BehaivourSubject 而不是 Subject

试试这个:

import { BehaviorSubject } from 'rxjs/BehaviorSubject';

服务

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);
    }

行为主题与主题

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

我想这应该行得通

我通过修改叉子做了类似的事情 Component Interaction