Angular 4 Service observable ne fonctionnant pas pour une API http.Angulaire 4 Service observable ne fonctionnant pas pour une API http get
Le http qui renvoie un observable ne semble pas fonctionner.
J'utilise la nouvelle HttpClient
Ceci est l'erreur que je reçois:
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
Solution?
It doesn't seem to like Observable going to the ngFor. Maybe I need to do a switchMap? in the component.
Ceci est mon appel de service http:
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/retry';
import { User } from "../models/user.model";
@Injectable()
export class UserService {
private baseUrl = "http://jsonplaceholder.typicode.com/users";
constructor(private http: HttpClient) {
}
getUsers(): Observable<User[]> {
return this.http.get<User[]>(this.baseUrl)
.retry(2)
.catch(e => this.handleError("Get Users Error", e));
}
private handleError(errorMessage: string, error: Object): any {
console.log(errorMessage, error);
}
};
Ceci est mon html:
<div class="column" *ngFor="let user of listOfUsers | async; let i = index">
<p>{{i + 1}}.{{user.name}}</p>
</div>
Ceci est mon élément:
import { Component, OnInit } from "@angular/core";
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/do';
import { UserService } from "../../services/user.service";
import { User } from "../../models/user.model";
@Component({
selector: "home-users",
templateUrl: "./home.component.html"
})
export class HomeComponent implements OnInit {
private listOfUsers: Observable<User[]>;
loading: boolean;
constructor(private userService: UserService) {}
ngOnInit() {
this.getUsers();
}
getUsers(): void {
this.loading = true;
this.listOfUsers = this.userService.getUsers().do(_ => this.loading = false);
}
}
Ceci est mon modèle:
export class User {
name: string;
};
Si vous utilisez angualr 4.3, utilisez le tutoriel suivant https://angular.io/guide/http car HttpClient n'a pas besoin de map et de json. –