angular2 http请求重复多次

时间:2016-06-13 05:25:20

标签: angular

今天我用angular 2写了一个http请求。我得到了服务中的数据,但我在component得到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(); }); } 。我不知道如何解决它,请给我一些帮助

服务

export class AdminComponent {
admins:Object;

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

}

的console.log(数据)

enter image description here

的console.log(RES) enter image description here

成分<​​/ P>

            <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>

}

模板无法获取数据

        var xhr = new XMLHttpRequest();
        xhr.open("GET", "http://localhost:5000/test", true);
        xhr.send();
        console.log(xhr.responseText);

1 个答案:

答案 0 :(得分:0)

每次Angular调用变更检测时,都会调用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;
        });
  }