Angular 4 Observable服务不适用于api http get [英] Angular 4 Observable service not working for an api http get
问题描述
Angular 4 Observable服务不适用于api http get.
Angular 4 Observable service not working for an api http get.
返回可观察值的http似乎不起作用.
The http that returns an observable doesnt seem to work.
我正在使用新的HttpClient
I'm using the new HttpClient
这是我得到的错误:
错误:找不到与之不同的支持对象"[object Object]" 输入对象". NgFor仅支持绑定到Iterables,例如 数组.
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
解决方案?
进入ngFor似乎并不喜欢Observable.也许我需要 做一个switchMap?在组件中.
It doesn't seem to like Observable going to the ngFor. Maybe I need to do a switchMap? in the component.
这是我的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;
};
推荐答案
当然,如果将Home Component更改为以下内容,它将解决您的问题?
Surely if you change your Home Component to the following it will resolve you issue?
getUsers(): void {
this.loading = true;
this.userService.getUsers().subscribe((users) => {
// --> Observable<T> returns here
this.listOfUsers = users; // or if json: this.listOfUsers = users.json();
},
(errors) => {
// --> Errors are returned here
},
() => {
// --> always called when finished
this.loading = false;
});
}
编辑
您必须将返回的数据映射为异步:
You'll have to map the returned data for async:
this.listOfUsers = this.userService.getUsers().map((data)=> return data.json() || []);
this.works fine on my side, check out this article: angular-2-async-pipe-example
这篇关于Angular 4 Observable服务不适用于api http get的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!