【问题标题】:Angular 2 http.get call, Array length is 0Angular 2 http.get 调用,数组长度为 0
【发布时间】:2017-04-18 06:35:46
【问题描述】:

我很难理解为什么我的数组是空的,我有一个 ASP.Net api ctr,我用 angular 2 服务调用它。 但由于某种原因,角度服务结果我是空的?当我调试时,我可以看到 API 返回了一个卡片类型的列表。因此,不是 api 没有返回结果。

这是我的打字稿 CardModel:

export class Card {
cardId: string;
name: string;
cardset: string;
type: string;
faction: string;
rarity: string;
cost: string;
attack: string;
health: string;
durability: string;
text: string;
inGameText: string;
flavor: string;
artist: string;
collectible: string;
elite: string;
race: string;
playerClass: string;
howToGet: string;
img: string;
imggold: string;
locale: string;
mechanics: string[];

}

这是我的 Angular 2 服务,当我调试该服务时,我可以看到在 Init 上调用了该服务,所以这不是问题,

getCards(): Observable<Card[]> {


    return this.http.get(this.cardsUrl)
        .map((res: Response) => res.json().data as Card[])
        .catch((error: any) => Observable.throw(error.json().error || 'Server error'));

}

这里是调用服务的组件,

ngOnInit(): void {
    this.loadCards();
}

loadCards() {
    return this.cardService.getCards()
        .subscribe(
        card => this.cards = card,
        err => {
            console.log(err);
        });
}

你们中有人知道问题可能是什么吗?

编辑: 这是我希望显示数据的地方

<table>
<thead>
    <tr>
        <th>
            Name
        </th>
    </tr>
</thead>
<tbody>
    <tr *ngFor="let card of cards">
        <td>{{card.name}}</td>
    </tr>
</tbody>
</table>

【问题讨论】:

  • 你在哪里使用这个数组? (this.cards)
  • 在表格中我可以发布我如何使用它
  • 为什么在 Angular 2 模板中使用 Angular 1 标记?
  • 当我调试时,我可以看到 API 返回了一个 Card 类型的列表:将 console.log() 添加到您的代码中,并将打印结果添加到您的问题,以便我们也可以看到该调试信息。
  • 它是 *ngFor,而不是 *ng-for。阅读文档。阅读您得到的(现已删除,但正确)答案。小心点。

标签: angular typescript


【解决方案1】:

ng-repeat 是 Angular1 语法。在 Angular2 中使用 ngFor 代替。

例子:

@Component({
  selector: 'my-app',
  template: `Hello World
  <tr *ngFor="let card of cards">
    <td>{{card?.name}}</td>
  </tr>`,
  directives: [],
  providers: []
})
export class AppComponent {
    private cards;
    constructor(){
      this.cards = [{name: 1},{name: 2},{name: 3}];
    }
}

以下是完整示例:http://plnkr.co/edit/pJWkLtiYonUpJfjZjCGd?p=preview

loadCards() {
    return this.cardService.getCards()
        .subscribe(
        (card) => {
          this.cards = card;
          console.log(this.cards); // Does this print undefined?
        },
        err => {
            console.log(err);
        });
}

【讨论】:

  • 所以现在它抱怨不能绑定到'ng-forIn',因为它不是'tr'的已知属性。你不能再在 tr 上呼叫中继器了吗?
  • directives: [FormsModule] 不正确。而且导入也没用。
  • @JBNizet 谢谢。我忘了ngFor 是一个内置指令。
  • 不是。顾名思义,FormsModule 是一个模块,而不是指令。 NgModule 的 directives 属性不应该再使用了,plunkr 无论如何也不会使用任何形式。
  • @JBNizet 是的,我已经更新了我的答案和 plunker。
猜你喜欢
  • 2019-01-31
  • 2017-11-10
  • 2014-07-27
  • 2017-11-26
  • 2016-11-23
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
  • 2016-06-29
相关资源
最近更新 更多