我有一个问题,我不知道为什么在可观察的条件下使用值变量时在我的视图中未更新它,
import { Component, OnInit } from '@angular/core';
import { Observable, Observer } from 'rxjs';
@Component({
selector: 'app-observables',
templateUrl: './observables.component.html',
styleUrls: ['./observables.component.css']
})
export class ObservablesComponent implements OnInit {
observable: Observable<number>;
value: number = 0;
observer: Observer<number>;
constructor() { }
ngOnInit() {
this.value = 10;
this.observable = new Observable((observer: Observer<number>) => {
this.observer = observer;
});
this.observable
.subscribe(this.handleData, this.handleError, this.handleComplete);
this.observer.next(12);
this.observer.next(15);
//this.observer.complete();
this.observer.next(16);
}
handleData(data) {
this.value = data;
console.log('Here are the usable data', data);
}
handleComplete() {
console.log('Complete');
}
handleError(error) {
console.log('error:', error)
return Observable.throw(error);
}
}
这是我的观点:
{{ value }}
答案 0 :(得分:3)
问题是代码丢失了this
(已重新分配)。您可以使用箭头功能解决此问题。
this.observable.subscribe((data) => this.handleData(data), (error) => this.handleError(error), () => this.handleComplete());
将成员分配给箭头函数,而不是将其声明为本质上的函数,也可以解决此问题。
handleData = (data) => {
this.value = data;
console.log('Here are the usable data', data);
}
handleComplete = () => {
console.log('Complete');
}
handleError = (error) => {
console.log('error:', error)
return Observable.throw(error);
}
答案 1 :(得分:0)
您不需要observer
,只需要拥有subject
,就可以next
和{{1 }}像往常一样,通过传递回叫或内联函数
complete