Angular 2中的服务不会将值重定为html组件

时间:2017-01-24 00:33:26

标签: angular

我是Angular 2的新手。我在本地计算机上托管了一项服务。服务很好。但是,当我要从我的Angular 2中的服务中检索数据时。如下所示:数据已成功检索并登录到我的控制台。但是,当我要在我看来展示价值观时。 " this.myPurchaseItems"是空的。这是为什么?请帮忙。谢谢

calling file......
this._service.getMyPracticeTest(this.uid).subscribe(data => {  this.myPurchaseItems = data }); 
------------------------------------------------------

service.ts file..... 
getMyPracticeTest(uid: string){
    return this._http.get('http://localhost:49753/RestServiceImpl.svc/getMyPracticeTest/' + uid)
        .map(res => res.json())
        .do(data => console.log("GetMyPracticeTest" + JSON.stringify(data)))
        .catch(this.handleError);
}
------------------------------------------------------

 <table class="table">
      <tr><th>ID</th></tr>
      <tr *ngFor="let data of myPurchaseItems">
          <td>{{data.Purchase_ID}}</td>
      </tr>
 </table>

解决问题的方法。

getMyPracticeTest(uid: string){
    return this._http.get('http://localhost:49753/RestServiceImpl.svc/getMyPracticeTest/' + uid)
    .map(data => {
        data.json();
        // the console.log(...) line prevents your code from working 
        // either remove it or add the line below (return ...)
        console.log("I CAN SEE DATA HERE: ", data.json());
        return data.json();
}

2 个答案:

答案 0 :(得分:0)

你没有太多东西可以继续,但我最近遇到了*ngFor绑定问题,并按照你的方式调用它。而是尝试这个

<tr *ngFor="let Purchase_ID of myPurchaseItems.data">
    <td>{{Purchase_ID}}</td>
</tr>

为我做了这件事,如果这不起作用,请将代码发布到您的组件和服务中,这样我们就可以更好地了解您正在做的事情。

答案 1 :(得分:0)

之前我遇到过类似的问题,问题是没有运行变更检测。

您可以在组件构造函数

中尝试此操作吗?
constructor(private cdRef:ChangeDetectorRef) { }

在完成块内

this._service.getMyPracticeTest(this.uid).subscribe(data => 
 {  
   this.myPurchaseItems = data;  
   this.cdRef.detectChanges();
 }); 

ChangeDetectorRef是从@angular/core

导入的

您可以阅读有关ChangeDetectorRef Here

的更多信息