I don't understand why this does not work but the alternatives below do.
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>
When I'm clicking the "increase counter" button, it first gets values, but not afterward, while these alternatives work just fine:
changeValue() {
this.fakeApiCall(this.id++)
.subscribe(this.obs)
.unsubscribe();
}
or
changeValue() {
this.fakeApiCall(this.id++)
.pipe(take(2)) // NOTES: if I write take(1), it has the same effect.
.subscribe(this.obs);
}
I am confused is this a bug or what's really going on here?
EDIT: if you want stackblitz url, here: https://stackblitz.com/edit/angular-28eyiy