我为我的< select>设置了数据集异步加载.我使用hot observable,因为数据可以及时改变.问题是我无法设置选定的值,并且Angular也没有指向第一个元素(在用户执行之前没有设置值).我正在尝试订阅我自己的观察结果……它不起作用,我想知道为什么?我怎么解决这个问题?
PLNKR:https://plnkr.co/edit/uDmTSHq4naYGUjjhEe5Q
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
<select [(ngModel)]="selectedValue">
<option *ngFor="let value of (values$| async)"
[value]="value">{{ value }}
</option>
</select>
`,
})
export class App implements OnInit, OnDestroy {
public name: string;
public selectedValue: string = '';
public values$: Observable<Array<string>> = new Observable(observer => this.observer = observer);
protected observer: Subscriber<Array<string>>;
protected subscription: Subscription;
constructor() {
this.name = `Angular! v${VERSION.full}`
}
ngOnInit() {
this.subscription = this.values$.subscribe((values) => {
console.log('never fired...');
this.selectedValue = values[0];
});
setTimeout(() => {
this.observer.next(['some', 'test', 'data']);
});
}
ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
解决方法:
您订阅了两次您的观察.订阅后异步管道在内部执行.
当正在执行subscribe方法时,它执行subscribe函数
observer => this.observer = observer
并覆盖this.observer属性,因此它只对异步管道(最后一个订阅者)有效
我会用share运算符来解决它
new Observable(observer => this.observer = observer).share();
要了解为什么this.observer被覆盖,只需运行此代码即可
let myObserver;
const observable$= new Rx.Observable(function subscribe(observer) {
console.log('subscribe function has been called');
myObserver = observer;
});
observable$.subscribe(function next1() { console.log('next1'); });
observable$.subscribe(function next2() { console.log('next2'); });
observable$.subscribe(function next3() { console.log('next3'); });
myObserver.next();
正如我所提到的,早期的异步管道在内部订阅了observable
https://github.com/angular/angular/blob/4.3.x/packages/common/src/pipes/async_pipe.ts#L23
原文地址:https://codeday.me/bug/20190611/1217183.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。