0

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

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

每个文件的内容是:

引导.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());
    }
}

pel.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"}

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

提前致谢!!

4

1 回答 1

1

你有一个<div *ngFor="#peli of pelis">元素。你在this.pelis这里设置为一个对象=>

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

你得到一个

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

由于 pelis 不是数组,因此您会收到此错误。

例如:代替

data => this.pelis = data

尝试:

data => this.pelis = [data]
于 2016-05-11T18:30:00.837 回答