2017-02-09 96 views
0

我有兩個子組件之間共享信息的Angular 2服務,兩個組件都與服務通信良好,但我無法將值設置爲服務中的變量。這裏是服務的代碼:Angular 2中的服務變量

import { Injectable } from '@angular/core'; 
import { Http, Headers, Response } from "@angular/http"; 
import { Observable } from "rxjs"; 
import { Subject } from 'rxjs/Subject'; 
import {BehaviorSubject} from 'rxjs/Rx'; 
import 'rxjs/Rx'; 

@Injectable() 
export class ServiceNotifications { 

    newPacient: boolean; 

    nuevoPacient$: Subject<boolean> = new BehaviorSubject<boolean>(this.newPacient); 

    constructor() { 
     this.newPacient$.asObservable(); 
    } 

    notiNewPacient(status:boolean){ 
     console.log(status); 
     this.newPacient=status; 
     this.newPaciet$.next(this.newPacient); 
    } 
} 

我的問題是,我不能更新變量newPacient與功能notiNewPacient()。

+0

'newPaciet $'沒有在任何地方定義,但也許這是一個錯字。你是什​​麼意思,你不能更新變量?此外,您的構造函數不會執行任何操作。 – rob

+0

每次創建pacient時,我都想用「true」值更新「newPacient」。我試圖用「notiNewPacient()」來做到這一點,但我無法得到它。該服務運行良好。組件連接到Observable。 – Osmon

回答

0

嘗試沒有觀察。

在服務:

constructor() { 
    this.newPacient$ = true; 
} 

在您的組件:

constructor(service: serviceNotifications) { 
} 

get newPacient(): boolean { 
    return service.newPacient; 
} 

然後,如果你想從組件訪問newPacient,你可以用this.newPacient這樣做。而從這個角度來看,只是newPacient