Angular 2中的服务变量
问题描述:
我有两个子组件之间共享信息的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()。
答
尝试没有观察。
在服务:
constructor() {
this.newPacient$ = true;
}
在您的组件:
constructor(service: serviceNotifications) {
}
get newPacient(): boolean {
return service.newPacient;
}
然后,如果你想从组件访问newPacient,你可以用this.newPacient
这样做。而从这个角度来看,只是newPacient
。
'newPaciet $'没有在任何地方定义,但也许这是一个错字。你是什么意思,你不能更新变量?此外,您的构造函数不会执行任何操作。 – rob
每次创建pacient时,我都想用“true”值更新“newPacient”。我试图用“notiNewPacient()”来做到这一点,但我无法得到它。该服务运行良好。组件连接到Observable。 – Osmon