具有http服务承诺的Angular 2更新组件变量

时间:2016-10-14 09:33:48

标签: angular typescript ionic2

我目前正在学习角度2和打字稿到目前为止似乎进展顺利但是我在创建服务时遇到了一些麻烦我更新了我称之为的组件中的数组,尽管该服务的所有数据都是在我的模板中以ng-for显示。

    ***people-service.ts***

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the PeopleService provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class PeopleService {
  constructor(public http: Http) {

  }

  load() {
    return new Promise(resolve => {
      this.http.get('http://api.randomuser.me/?page=3&results=30')
        .map(res => res.json())
        .subscribe(data => {
          data = data.results;
          resolve(data);
        });
    });
  }

}

上面是我创建的服务,它返回来自api的承诺中的json数据。

***about.ts***
import { Component, ViewChild, ElementRef } from '@angular/core';

import { NavController, Content } from 'ionic-angular';
import { PeopleService } from '../../providers/people-service';

@Component({
    selector: 'page-about',
    templateUrl: 'about.html',
    providers: [PeopleService]
})
export class AboutPage {

    public people: any;

    constructor(public navCtrl: NavController, public peopleService: PeopleService) {
        this.peopleService.load().then(data => {
            this.people = data;
        });
        console.log(this.people);
    }
}

在上面的组件加载我的构造函数中的数据,它在模板中显示得很好,就像我说的那样但是console.log(this.people)显示未定义我希望有人可以帮我弄清楚我在这里缺少什么。我想我必须对从服务返回数据的方式或我尝试记录数据的点做错。对于任何感兴趣的人来说,主要目标是this.people / 2来获取数组中的中间对象,并在页面加载时滚动它。

2 个答案:

答案 0 :(得分:3)

this.peopleService.load()是一个异步函数,这意味着:

  1. 执行load()函数
  2. 执行console.log
  3. data从serer返回,this.people = data已执行。
  4. 您希望将console.log置于设置load()的{​​{1}}回调函数中,以便您可以打印实际数据,如下所示:

    this.people = data

答案 1 :(得分:1)

尽量避免将Observable包装到Promises中,或者将Promise包装到Observables并编写服务方法,以便它们返回一个Observable。 (除非你有充分的理由不这样做:)

@Injectable()
export class PeopleService {
  constructor(public http: Http) { }

  load() {
    // DON'T 
    return new Promise(resolve => {
      this.http.get('http://api.randomuser.me/?page=3&results=30')
        .map(res => res.json())
        .subscribe(data => {
          data = data.results;
          resolve(data);
        });
    });
    // DO: 
    return this.http.get('http://api.randomuser.me/?page=3&results=30')
      .map(res => res.json())
  }

}

在服务中,您设置了一种获取数据的方法,并在您的组件(您实际需要数据的地方)中订阅到服务返回的observable以获取数据:

export class AboutPage {
    public people: any;

    constructor(public navCtrl: NavController, public peopleService: PeopleService) {
        this.peopleService.load().subscribe(data => {
            this.people = data;
            console.log(this.people);
        });
    }
}