我有一个replaySubject变量正在服务上更新,组件正确地获取了新的值,但是它似乎没有更新视图(HTML中的绑定保持为空,即使变量已正确更新)。
服务:
export class ExampleService {
myVariable;
constructor(private http: HttpClient, private userModel: UserModel) {
this.myVariable = new ReplaySubject(1);
this.getApiRoot(`/api/endpoint`)
.subscribe(
data => {
this.myVariable.next(data);
},
err => {
console.log(`Database connection error: ${err}`);
},
() => { }
);
}
}
组件:
导入example service自'。/example.service';
导出类MyComponent实现OnInit{
valueOnFrontend: string;
constructor(exampleService: ExampleService) {};
ngOnInit() {
this.exampleService.myVariable.subscribe(
function(value) {
console.log(this.valueOnFrontend);
this.valueOnFrontend = value;
},
function(error) {
console.log(err);
},
function() {
console.log("Request completed.");
}
)
}
}
和HTML
ExampleService
如下所示:
{{ valueOnFrontend }}
因此,该值在服务中被正确地更新,然后被正确地发送到组件,
console.log
在组件中记录新值,但是HTML绑定没有得到更新。
我读到RXJS在它自己的区域中运行,而角区域不知道其中的更新。如何修复此问题,并在HTML中获取要更新的值?
谢谢。:p