Angular 4 Observable服务不适用于api http get

时间:2017-09-06 10:00:34

标签: angular angular-http angular-observable

Angular 4 Observable服务不适用于api http get。

返回可观察的http的http似乎无效。

我正在使用新的HttpClient

这是我得到的错误:

  

错误:无法找到不同的支持对象'[object Object]'   输入'对象'。 NgFor仅支持绑定到Iterables,例如   阵列。

解决方案吗

  

它似乎不喜欢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;
};

2 个答案:

答案 0 :(得分: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);
}

}

新的HttpClient没有使用json方法定义Response类。而不是现在,开发人员可以将HTTP方法与类型参数一起使用。

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

enter image description here

答案 1 :(得分:1)

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

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