0

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;
};
4

2 回答 2

2

当然,如果您将 Home 组件更改为以下内容,它会解决您的问题吗?

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;
        });
}

编辑

您必须将返回的数据映射为异步:

this.listOfUsers = this.userService.getUsers().map((data)=> return data.json() || []);

this.works 对我来说很好,看看这篇文章:angular-2-async-pipe-example

于 2017-09-06T11:16:43.543 回答
1

进行以下更改:

export interface User {
  name: string;
};

@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: HttpErrorResponse | any){
  console.log(errorMessage, error);
}

}

新的没有用 json 方法HttpClient定义一个类。Response现在开发人员可以使用带有类型参数的 HTTP 方法来代替它。

这是我的控制台错误的屏幕截图:

在此处输入图像描述

于 2017-09-06T10:09:58.453 回答