Angular 2 http.get调用,数组长度为0

时间:2016-12-03 12:15:23

标签: angular typescript

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

这是我的打字稿CardModel:

$jsonencode->extractorData->data[0]->group[0]->Hora

}

这是我的角度2服务,我可以看到,当我调试在Init上调用服务时,这不是问题,

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[];

这是调用服务的组件,

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);
        });
}

1 个答案:

答案 0 :(得分:2)

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);
        });
}