Angular 4 Observable 服务不适用于 api http get。
返回 observable 的 http 似乎不起作用。
我正在使用新的 HttpClient
这是我得到的错误:
错误:找不到“object”类型的不同支持对象“[object Object]”。NgFor 仅支持绑定到 Iterables,例如 Arrays。
解决方案?
似乎不喜欢 Observable 去 ngFor。也许我需要做一个switchMap?在组件中。
这是我的 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);
}
};
这是我的html:
<div class="column" *ngFor="let user of listOfUsers | async; let i = index">
<p>{{i + 1}}.{{user.name}}</p>
</div>
这是我的组件:
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);
}
}
这是我的模型:
export class User {
name: string;
};