I am facing an issue with my HTTP service that returns information based on a given item ID. The data is fetched using a Subject
, which receives the initial data in the ngOnInit
method.
To display the returned data in the HTML, I utilize the async
pipe.
The problem arises when the async
pipe has not subscribed to the observables before I call selections.next
with the first item ID, causing it not to be displayed during initialization.
Is there a way to ensure that the async
pipe subscribes to the Observable
before sending the initial data to the subject for the first HTTP request?
I have experimented with various lifecycle hooks, but none seem to resolve the issue.
import { Component, OnInit } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Subject } from "rxjs/Subject";
import { ExampleService } from "./example.service";
import "rxjs/add/operator/switchMap";
@Component({
template: `
<div>
<div *ngFor="let time of times | async">{{ time }}</div>
</div>
`,
})
export class ExampleComponent implements OnInit {
times: Observable<string[]>;
constructor(
private exampleService: ExampleService
) { }
ngOnInit() {
var itemIds = new Subject<number>();
this.times = itemIds
.switchMap(itemId => this.exampleService.getData(itemId))
.map(data => this.calculateTimes(data));
// Provide an item ID to the subject.
// This is also performed periodically as well as
// during initialization.
itemIds.next(10);
}
calculateTimes(data: string[]) {
/*
* Some processing code.
*/
return data;
}
}