首页 文章

Angular2 ngFor:我做错了什么?

提问于
浏览
5

我难以克服“无法找到'对象'类型的'对象对象''的错误”这个错误似乎与Angular2非常相似,我希望有人遇到类似的东西 .

这是来自我服务的(匿名)JSON,非常简单:

[
    {
        "item_id": 1,
        "item_type": 2,
        "item_name": "Item 1",
        "item_description": "First item"
    },
    {
        "item_id": 2,
        "item_type": 4,
        "item_name": "Item 2",
        "item_description": "Second item"
    }
]

这是描述这些对象的类,服务和组件的内容:

// item.ts
export class Item {
    item_id: number;
    item_type: number;
    item_name: string;
    item_description: string;
}

//item.service.ts snippet
getItems(): Promise<Item[]> {
    return this.http.get('http://apiurl', { withCredentials: true })
    .toPromise()
    .then((response) => {
        let body = response.json();
        return body as Item[];
    })
    .catch(this.handleError);
}

//item.component.ts snippet
items: Item[];

getItems(): void { // Function that calls the item service
    this.itemService
    .getItems()
    .then((items) => {
        console.log(items); // I use this to verify that I'm getting an array.
        this.items = items;
    });
}

最后,ngFor组件:

<ul>
    <li *ngFor="let item of items">
        <i class="fa fa-database"></i> {{item.item_name}}
    </li>
</ul>

我没有看到任何部分的任何错误 . 检索到的数据肯定会到达项目组件,这意味着我的导入是正确的,并且我的console.log中显示的内容绝对是一个数组,具有 __proto__:Array[0] 属性和所有内容 . 如果我登录Angular教程Heroes应用程序,它甚至看起来与输出的内容相同 . 然而,它根本不会迭代数组,坚持认为它是一个对象 .

我究竟做错了什么? ngFor刚刚坏了吗?

Edit 这是完整的(匿名)类,删除了不相关的位:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Headers, Response, Http, RequestOptions } from '@angular/http';
import { Item } from '../../classes/item/item';
import { ItemService } from '../../services/item/item.service';

@Component({
    moduleId: module.id,
    selector: 'my-items',
    templateUrl: 'items.component.html'
})
export class ItemComponent implements OnInit {
    items: Item[] = [];

    constructor(
    private router: Router,
    private itemService: ItemService
    ) { }

    getItems(): void {
        console.log(this.items);
        this.itemService
        .getItems()
        .then((items) => {
            console.log(items);
            this.items = Array.from(items);
        });
    }

    ngOnInit() {
        this.getItems();
    }
}

Edit 2

我知道了!我认为它可能是Angular2中的一个错误 . 上面,我使用名为“items”的通用变量名称清理了我的代码 . 但在真实的 生产环境 代码中,变量被称为“实体” . 而且在整个过程中,我都有这样的名字 . 一时兴起,我将变量的名称更改为“testentities”,并且它有效!

所以,为了确保,我测试了多种变体,并且每次都有效 . 然后我将其改回“实体”,错误再次出现 . 它似乎是某种保留变量 .

我会严格测试一下,如果它一致可重复,我会在bug跟踪器上报告 .

1 回答

  • 1

    试一试

    item.service.ts 片段

    getItems(): Promise<Item[]> {
        return this.http.get('http://apiurl', { withCredentials: true })
        .toPromise()
        .then((response) => {
            let body = response.json();
            return body;
        })
        .catch(this.handleError);
    }
    

    item.component.ts 片段

    items: Item[] = []; // For whatever reason it thinks this is an Object
    
    getItems(): void { // Function that calls the item service
        //this.items = Array.from(this.items);
        this.itemService.getItems().then(items => this.items = items);
    }
    

    [更新]

    嗯,你已经耗尽了我的调试资源,所以我将把它带到基础,

    Angular 2 HTTP Client是他们向您展示如何发出 GET 请求的地方 . 然后HERE是基于Promise的设置 .

    所以,这就是你应该看起来的样子 .

    item.service.ts 片段

    getItems(): Promise<Item[]> {
        return this.http.get('http://apiurl', { withCredentials: true })
        .toPromise()
        .then(this.extractData)
        .catch(this.handleError);
    }
    private extractData(res: Response) {
      let body = res.json();
      return body || { };
    }
    private handleError (error: any) {
      // In a real world app, we might use a remote logging infrastructure
      // We'd also dig deeper into the error to get a better message
      let errMsg = (error.message) ? error.message :
        error.status ? `${error.status} - ${error.statusText}` : 'Server error';
      console.error(errMsg); // log to console instead
      return Promise.reject(errMsg);
    }
    

    item.component.ts

    items: Item[] = [];
    
    getItems(): void {
      this.itemService.getItems().then(items => this.items = items);
    }
    

    更新#2

    这听起来像是OP解决了他的问题并且它与其中一个变量的名称有关,看起来名为 entites 的变量可能会导致Angular 2中断 .

    “但是在真实的 生产环境 代码中,变量被称为”实体“ . 在整个过程中,我已经将它命名为” . “一时兴起,我将变量的名称更改为”testentities“,它确实有效!所以只是为了确保,我测试了多种变化,并且它每次都有效 . 然后我将它改回“实体”,错误再次出现 . “

    entities: any{};
    

相关问题