Angular 角度2中的服务变量

Angular 角度2中的服务变量,angular,typescript,Angular,Typescript,我有一个Angular 2服务,用于在两个子组件之间共享信息,这两个组件都与服务进行了良好的通信,但我无法将变量的值设置到服务中。以下是服务代码: import { Injectable } from '@angular/core'; import { Http, Headers, Response } from "@angular/http"; import { Observable } from "rxjs"; import { Subject } from 'rxjs/Subject';

我有一个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);
    }
}
从'@angular/core'导入{Injectable};
从“@angular/Http”导入{Http,Headers,Response};
从“rxjs”导入{observeable};
从'rxjs/Subject'导入{Subject};
从'rxjs/Rx'导入{BehaviorSubject};
进口“rxjs/Rx”;
@可注射()
导出类服务通知{
newPacient:布尔型;
nuevoPacient$:Subject=新行为主体(this.newPacient);
构造函数(){
此.newPacient$.asObservable();
}
notiNewPacient(状态:布尔){
控制台日志(状态);
这个.newPacient=状态;
this.newPaciet$.next(this.newPacient);
}
}

我的问题是,我无法使用函数notiNewPacient()更新变量newPacient。

在没有可观察变量的情况下尝试它

为您服务:

constructor() {
  this.newPacient$ = true;
}
在您的组件中:

constructor(service: serviceNotifications) {
}

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

然后,如果您想从组件访问newPacient,可以使用
this.newPacient
。从视图上看,只是
newPacient

newPaciet$
没有在任何地方定义,但这可能是一个打字错误。不能更新变量是什么意思?此外,您的构造函数没有做任何事情,我希望在每次创建pacient时都用“true”值更新“newPacient”。我正试图用“notiNewPacient()”来做这件事,但我做不到。服务很好。组件连接到可观察对象。