Angular2 HTTP请求失败

时间:2016-05-11 18:18:32

标签: angular angular2-http

这是我的第一个问题。我在API上的http请求有问题。当我发出请求时,控制台上会显示以下错误:

例外:找不到不同的支持对象' [object Object]'类型'对象'。 NgFor仅支持绑定到Iterables,例如Arrays。

每个文件的内容是:

boot.ts

import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from "./app.component";
import {HTTP_PROVIDERS} from "angular2/http";

bootstrap(AppComponent,[HTTP_PROVIDERS]);

app.component.ts

import {Component} from 'angular2/core';
import {HTTPTestService} from "./services/peli.service";
import {Peli} from "./peli";

@Component({
    selector: 'my-app',
    template: `
        <h1>Búsqueda de película</h1>
        <input #titulo placeholder="Buscar...">
        <button class="btn btn-success"     (click)="infoPeli(titulo.value)">Buscar</button>
        <div *ngFor="#peli of pelis">
        <h1>{{peli.Title}}</h1>
        <p>{{peli.Year}}</p>
        </div>
    `,
    providers: [HTTPTestService]
})

export class AppComponent {

pelis:Peli[];

    constructor (private _httpService: HTTPTestService) {}

    infoPeli(nombre:string) {
        this._httpService.buscarPeli(nombre)
            .subscribe(
                data => this.pelis = data,
                error => alert(error),
                () => console.log(this.pelis)
            );
    }
}

peli.service.ts

import {Injectable} from "angular2/core";
import {Http} from "angular2/http";
import 'rxjs/add/operator/map';

@Injectable()
export class HTTPTestService {
    constructor(private _http:Http) {
    }

    buscarPeli(nombre:string) {
        return this._http.get('http://www.omdbapi.com/?    t='+nombre+'&y=&plot=short&r=json').map(res => res.json());
    }
}

peli.ts

export class Peli{
    Title:string;
    Year:string;
}

我从请求中收到的JSON文件(输入 - 蜘蛛侠):

{"Title":"Spiderman","Year":"1990","Rated":"N/A","Released":"N/A","Runtime":"5 min","Genre":"Short","Director":"Christian Davi","Writer":"N/A","Actors":"N/A","Plot":"N/A","Language":"German","Country":"Switzerland","Awards":"N/A","Poster":"N/A","Metascore":"N/A","imdbRating":"5.7","imdbVotes":"90","imdbID":"tt0100669","Type":"movie","Response":"True"}

我不知道问题出在哪里,一切似乎都没问题......

提前致谢!!

1 个答案:

答案 0 :(得分:1)

您有一个<div *ngFor="#peli of pelis">元素。并且您将this.pelis设置为此处的对象=&gt;

.subscribe(
                data => this.pelis = data,

你得到了一个

EXCEPTION:找不到'object'类型的不同支持对象'[object Object]'。 NgFor仅支持绑定到Iterables,例如Arrays。

由于pelis不是数组,因此会出现此错误。

例如: 而不是

data => this.pelis = data

尝试:

data => this.pelis = [data]