Through (app.component.ts), I'm trying to get data from a service (mydb.service.ts) that displays after a delay of 10 seconds, and displays through the (aap.component.html) template.
mydb.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Restaurant } from './restaurant';
@Injectable({
providedIn: 'root'
})
export class MydbService {
private dbUrl = 'http://localhost:3000/api'; // URL to web api
constructor( private http: HttpClient ) { }
viewall(): Observable<Restaurant[]> {
// This code below delays return for 10 seconds (to simulate real life delays)
var start = new Date().getTime();
while ((new Date().getTime() - start) < 10000) {
n: 1;
}
console.log('10 secs over');
return this.http.get<Restaurant[]>(this.dbUrl+'/view');
}
}
app.component.ts
import { Component, OnInit } from '@angular/core';
import { Restaurant } from './restaurant';
import { MydbService } from './mydb.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'myangular';
restaurants$: Restaurant[];
constructor(private dbService: MydbService) { }
ngOnInit() {
this.viewrestaurants();
}
viewrestaurants(): void {
this.dbService.viewall()
.subscribe((restaurants) => {
this.restaurants$ = restaurants;
console.log(restaurants);
});
}
}
app.component.html
test<br>
<li *ngFor="let restaurant of restaurants$">{{restaurant.restaurantName}}</li>
According to my logic, test is supposed to be displayed initially without any delay, and after 10 seconds the <li> items are to be displayed.However, on starting Angular the complete data in (app.component.html) displays only after 10 seconds. How to display the <li> items asynchronously?