【发布时间】:2019-03-10 10:03:37
【问题描述】:
我不明白为什么这不起作用,但下面的替代方法可以。
app.component.ts
import { Component } from '@angular/core';
import { Subject, Observable } from 'rxjs';
import { first } from 'rxjs/operators';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
id = 0;
obs = new Subject();
changeValue() {
this.fakeApiCall(this.id++)
.pipe(first())
.subscribe(this.obs);
}
fakeApiCall(id: number) {
return new Observable(observer => {
console.log('called with id ' + id);
observer.next({ items: [id, Math.random()] });
});
}
}
app.component.html
<h1>
<div *ngIf="(obs | async) as v">
<ul>
<li *ngFor="let item of v.items">
{{ item }}
</li>
</ul>
<ul>
<li *ngFor="let item of v.items">
{{ item }}
</li>
</ul>
</div>
<div *ngIf="(obs | async) as v">
<ul>
<li *ngFor="let item of v.items">
{{ item }}
</li>
</ul>
<ul>
<li *ngFor="let item of v.items">
{{ item }}
</li>
</ul>
</div>
<button (click)="changeValue()">increase counter</button>
</h1>
当我单击“增加计数器”按钮时,它首先获取值,但不是之后,而这些替代方法工作得很好:
changeValue() {
this.fakeApiCall(this.id++)
.subscribe(this.obs)
.unsubscribe();
}
或
changeValue() {
this.fakeApiCall(this.id++)
.pipe(take(2)) // NOTES: if I write take(1), it has the same effect.
.subscribe(this.obs);
}
我很困惑这是一个错误还是这里到底发生了什么?
编辑:如果你想要 stackblitz 网址,这里:https://stackblitz.com/edit/angular-28eyiy
【问题讨论】: