I tried using the Angular async pipe and got it working to display the time I get from the server using a http get request. I have the following questions:
- If I want to re-execute the http get request again to get updated data, is it correct to do what I'm doing in testAsync(), or is there a more elegant way to do this?
- Also I noticed some flickering going on when using the async pipe and re-requesting the data. This does not happen in the non-async version ("testNormal()"). Is there any way to prevent this from happening?
Angular component:
@Component({
selector: 'app-async-test',
templateUrl: './async-test.component.html',
styleUrls: ['./async-test.component.scss']
})
export class AsyncTestComponent implements OnInit {
private readonly baseApiUrl = environment.baseApiUrl;
httpServerRequest$ = this.http.get<ServerTimeViewModel>(`${this.baseApiUrl}/admin/servertime`);
testNormalResult: Date = null;
testAsyncResult$: Observable<Date> = null;
constructor(
private http: HttpClient
) {}
ngOnInit() {
this.testAsync();
}
testNormal(): void {
this.httpServerRequest$.subscribe(data => {
this.testNormalResult = data.serverTime;
});
}
testAsync(): void {
this.testAsyncResult$ = this.httpServerRequest$
.map(d => d.serverTime);
}
}
ServerTimeViewModel class:
export class ServerTimeViewModel {
serverTime: Date;
}
template:
Test normal: {{ testNormalResult | date:'mediumTime'}}<br>
Test async: {{ testAsyncResult$ | async | date:'mediumTime'}}<br>
<button type="button" (click)="testNormal()">test normal</button>
<button type="button" (click)="testAsync()">test async</button>