首先,這與一些http請求無關,它是一種簡單的場景,其中一個組件設置一個布爾值,另一個組件根據它顯示/隱藏元素。Angular 4 Observable returns undefined
問題是其他組件在訂閱回調中總是收到'undefined'。但是,我試圖讓主要組件訂閱,並且它正確接收值。
這裏是我的代碼:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class EnablerService {
private _enabled= new Subject<boolean>();
get Enabled() { return this._enabled.asObservable(); }
SetEnabled(value: boolean) {
this._enabled.next(value);
console.log(`service: ${value}`);
}
}
主要成分:
import { Component } from '@angular/core';
import {EnablerService} from './enabler.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [EnablerService]
})
export class AppComponent {
title = 'app';
private _isEnabled: boolean;
constructor(public service: EnablerService) {
service.Enabled.subscribe(val => {
this._isEnabled = val;
console.log(`app comp: ${this._isEnabled}`);
});
}
Switch() {
this.service.SetEnabled(!this._isEnabled);
console.log('switched');
}
}
其他成分:
import { Component, OnInit } from '@angular/core';
import {EnablerService} from './enabler.service';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.css'],
providers: [EnablerService]
})
export class FooterComponent implements OnInit {
private _isEnabled: boolean;
constructor(private service: EnablerService) {
this._isEnabled = true;
}
ngOnInit() {
this.service.Enabled.subscribe(val => {
this._isEnabled = val; // this one here.
console.log(`footer comp: ${this._isEnabled}`);
});
}
}
主要成分結合Switch
方法一個按鈕,它的工作原理。控制檯輸出本上點擊:
應用比較:真正
服務:真
切換
不確定
再次點擊將true
值切換到false
但仍然給未定義。
任何人有一個想法這裏發生了什麼?
我不明白爲什麼'app comp:true'可以是真的。有些東西可以幫助你,開始初始化你的主題:'private _enabled = new Subject(false);' –
@ DeblatonJean-Philippe主題沒有帶參數的構造函數。 –
謝謝你,在這裏看到:https://stackoverflow.com/questions/43348463/what-is-the-difference-between-subject-and-behaviorsubject 我錯了。 –