Я не понимаю, почему это не работает, но альтернативы ниже.
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);
}
Я запутался, это ошибка или что здесь на самом деле происходит?
РЕДАКТИРОВАТЬ: если вы хотите, чтобы URL-адрес stackblitz, здесь: https://stackblitz.com/edit/angular-28eyiy