2016-06-13 90 views
2

今天我用angular 2写了一个http请求。我得到了服务中的数据,但我得到undefindedcomponent。我不知道如何解决它,请给我一些帮助。angular2 http请求重复多次

服务

export class AdminStoreService { 
    data:Object; 

    constructor(http:Http) { 
     this.http = http; 
    } 

    findAll() { 
    return this.http 
     .get('/data/admin.json') 
     .map((res:Response) => { 
      console.log(data); //can get the json data 
      this.data = res.json(); 
     }); 
} 

}

的console.log(数据)

enter image description here

的console.log(RES) enter image description here

部件

export class AdminComponent { 
admins:Object; 

constructor(adminStore:AdminStoreService) { 
    this._adminStore = adminStore; 
    this._adminStore.findAll().subscribe(data => this.admins = data); 
    console.log(this.admins); // undefined 
} 

}

模板无法获得数据

  <section *ngIf="admins"> 
       <tr *ngFor="let admin of admins" class="animated fadeInRight"> 
        <td>{{admin.username}}</td> 
        <td class="alert">{{admin.authLevel}}</td> 
        <td>{{admin.operator}}</td> 
        <td>{{admin.created | dateFormat:'YYYY-MM-DD HH:mm:ss'}}</td> 
        <td>{{admin.updated | dateFormat:'YYYY-MM-DD HH:mm:ss'}}</td> 
       </tr> 
      </section> 
+0

哪里或你怎么骂'getAdmins()'? –

+0

在模板中,我使用* ngFor – xiaomo

+0

源代码在github上:https://github.com/nodejs-study/node-koa/tree/master/web/admin – xiaomo

回答

0

每次角所调用变化检测,getAdmin()被调用,以检查它是否会返回一个不同的值作为最后的时间。

有不同的方法来解决这种情况

export class AdminComponent { 
    constructor(adminStore:AdminStoreService) { 
     this._adminStore = adminStore; 
     this._adminStore.findAll().subscribe(data => this.admins = data); 
    } 
} 

的服务也没有工作,它的构建方式。它应该像

export class AdminStoreService { 
    data:Object; 

    /** 
    * 构造函数 
    */ 
    constructor(http:Http) { 
    this.http = http; 
    } 

    findAll() { 
    return this.http 
     .get('/data/admin.json') 
     .map(res:Response => res.json()); 
    } 
} 

更新

获取调试输出

findAll() { 
    return this.http 
     .get('/data/admin.json') 
     .map(res:Response => res.json()) 
     .map(data => { 
      console.log(data); 
      return data; 
     }); 
    } 
+0

我将代码更改为服务中的代码,但出现TypeError错误:this.http.get(...)。map不是函数 – xiaomo

+0

http://stackoverflow.com/questions/34515173/angular-2-http-get-with-typescript-error -http-get-map-is-a-function-in –

+0

'this.admins'只在'data => this.admins =数据“被执行。这就是我修改你的findAll()方法的原因。 'data => this.admins = data'是传递给'subscribe'的回调函数。当服务器最终响应时,该回调将被执行。您可能希望在模板周围添加'

...
'或使用'admins?.someProp'来避免'this.admins'尚未设置时发生错误。 –