2017-09-25 101 views
1

首先,這與一些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但仍然給未定義。

任何人有一個想法這裏發生了什麼?

+0

我不明白爲什麼'app comp:true'可以是真的。有些東西可以幫助你,開始初始化你的主題:'private _enabled = new Subject (false);' –

+0

@ DeblatonJean-Philippe主題沒有帶參數的構造函數。 –

+0

謝謝你,在這裏看到:https://stackoverflow.com/questions/43348463/what-is-the-difference-between-subject-and-behaviorsubject 我錯了。 –

回答

4

當您將EnablerService置於組件的providers陣列中時,它將收到服務的新實例,而您需要在組件之間共享一個服務。您應該只在某些父組件中提供EnablerService(可能是AppRoot組件)並在子組件中使用它(注入它)。

的樣例用法見docs:只有MissionControlComponentMissionServiceproviders上市,AstronautComponent沒有 - 它只是注入。

+0

它現在的作品,謝謝你的回答,沒有注意到我只需要將它註冊爲供應商一次。 –

+0

我曾經有同樣的問題:)這個想法很快就在這裏描述:https://angular.io/guide/architecture#dependency-injection。 – tdragon

+0

我們不應該只在服務提供者app.module中注入服務,也不需要在每個組件中再次注入它作爲提供者 –