2016-12-03 51 views
-4

我有点麻烦理解为什么我的数组是空的,我有一个ASP.Net api ctr,我用角2服务调用。 但由于某种原因,角度服务结果为空?当我调试我可以看到API返回类型卡的列表。所以不是api,它不返回结果。Angular 2 http.get调用,数组长度为0

这里是我的打字稿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[]; 

}

,这里是我的角度分2次服,我可以看到,当我调试,该服务被称为在初始化,这样是没有问题的,

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

你们任何人都知道问题可能是什么?

编辑: 这里是我想要的数据是showen

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

你在哪里使用这个数组? ('this.cards') – echonax

+0

在表中我可以发布我如何使用它 –

+4

为什么在Angular 2模板中使用Angular 1标记? – jonrsharpe

回答

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

所以现在它抱怨无法绑定到'ng-forIn',因为它不是'tr'的已知属性。你不能再打一个tr的中继器吗? –

+1

'指令:[FormsModule]'不正确。而且导入也是无用的。 –

+0

@JBNizet谢谢。我忘了'ngFor'是一个内置的指令。 – echonax