I have a component loading a local json file (contains only name) from assets folder.Since HttpClient takes care of formatting data as json, so didn't use map here.
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators'
export type cont= {name: string};
@Component({
selector: 'my-app',
template: `
1st List
<ul>
<li *ngFor="let contact of contacts | async">{{contact.name}}</li>
</ul>
2st List
<ul>
<li *ngFor="let contact of contacts2 | async">{{contact.name}}</li>
</ul>
`
})
export class AppComponent {;
contacts: Observable<cont[]>;
contacts2: Observable<cont[]>;
constructor (http: HttpClient) {
this.contacts = http.get<cont[]>('http://localhost:4200/assets/contacts.json');
setTimeout(() => this.contacts2 = this.contacts, 500);
}
}
Contacts.json
{
"items": [
{ "name": "Mark Twain" },
{ "name": "Sherlock Holmes" }
]
}
Data can be fetched on browser via http://localhost:4200/assets/contacts.json but When I tried to render the same via async pipe I get this error below.Tried many ways to convert observable to Observable<[]> but none passed this scenario. What's wrong here. how json data over httpclient can be converted to Array ? (tried to follow similar posts but none helped)?
setTimeout()
, you will not be able to control how quickly the response will resolve and that is exactly why RxJS operators such asmap()
exist, even just to extract data from nested properties. - Alexander Staroselsky