Reputation: 13
I've created an angular app which gets data from a local json file. But I'm having issues with showing the data in html. A lot of variables are in dutch, I'm sorry for that, I'm a bit new to all of this :)
This is my service:
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { City } from './city';
@Injectable({
providedIn: 'root'
})
export class WeatherService {
citiesListUrl = "assets/city.list.json";
constructor(private http: HttpClient) {
}
public getCities(): Observable<HttpResponse<City[]>>{
return this.http.get<City[]>(this.citiesListUrl, {observe: 'response'})
.pipe(retry(3), catchError(this.handleError)
);
}
}
This is the component:
import { Component, OnInit, HostListener } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { WeatherService} from './weather.service';
import { Observable } from 'rxjs';
import { City } from './city';
@Component({
selector: 'app-weather',
templateUrl: './weather.component.html',
styleUrls: ['./weather.component.css'],
providers: [WeatherService]
})
export class WeatherComponent implements OnInit {
public cities:City[];
headers;
error;
constructor(private weatherService: WeatherService) { }
public getCities(){
this.weatherService.getCities()
.subscribe(resp => {
// display its headers
const keys = resp.headers.keys();
this.headers = keys.map(key =>
`${key}: ${resp.headers.get(key)}`);
// access the body directly.
this.cities = { ... resp.body }},
error => this.error = error);
}
ngOnInit() {
this.getCities();
}
}
And this is HTML code:
<div class="row">
<div class="col">
<ul>
<li *ngFor="let ci of cities">
{{ci.name}}
</li>
</ul>
</div>
</div>
I´ve tried with another answer they´re Angular 4 develop thought, they didn´t work over my code. I´ve tried with async pipe too but it works.
Upvotes: 0
Views: 3032
Reputation: 13
this solved my issue
getBooks()
{
this.isbnsource.getBooks(this.isbn).subscribe(
data => { this.foundBooks = data.json();
this.foundBooks = Array.of(this.foundBooks);
},
err => console.error(err), `enter code here`
() => console.log('getBooks completed')
);
}
Upvotes: 0
Reputation: 86740
this.cities = { ... resp.body }},
This should be
this.cities = [ ... resp.body ]
As error stated that *ngFor
will only iterate over the array not on object so you need to push your JSON data into array as I mentioned.
Upvotes: 3