【发布时间】:2017-12-20 16:42:18
【问题描述】:
我为我的<select> 设置了异步加载的数据。我使用 hot observable,因为数据会随时间变化。问题是我无法设置选定的值,而且 Angular 本身也没有指向第一个元素(在用户这样做之前没有设置值)。我正在尝试订阅我自己的 observable 并且......它不起作用,我想知道为什么?我该如何解决这个问题?
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();
}
}
}
【问题讨论】:
标签: javascript angular typescript rxjs angular-forms