如何检查提供程序以查看HTTP数据是否已就绪

时间:2016-03-20 05:35:59

标签: javascript angularjs angular

我正在使用离子beta框架进行移动开发,它使用Angular2,所以我认为这更像是一个Angular2问题,因为它更多地涉及使用提供程序进行HTTP调用。

我的应用程序从app.js开始。在这个文件中,我调用我的提供者进行HTTP调用以在后台获取一些信息。当发生这种情况时,用户离开app.js并转到另一个页面page.js.在后台,http呼叫仍在进行并且已完成。页面应显示来自提供程序的数据,但数据尚未准备好。我是Angular的新手,我不确定如何处理这种情况。在我的页面中,如何调用我的提供程序,检查调用的状态(查看数据是否准备就绪,是否发生错误,或者是否进行了调用),并获取数据是否已准备好?

我的app.js:

import {App, Platform} from 'ionic-angular';
import {TabsPage} from './pages/tabs/tabs';
import {FacebookFriends} from './providers/facebook-friends/facebook-friends';


@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  providers: [FacebookFriends],
  config: {} // http://ionicframework.com/docs/v2/api/config/Config/
})
export class MyApp {
  static get parameters() {
    return [[Platform]];
  }

  constructor(platform:Platform,facebookFriends:FacebookFriends) {
    this.rootPage = TabsPage;

    this.fb = facebookFriends;

    platform.ready().then(() => {

        this.fb.load().then((success)=>{
            if(success){
              console.log('success = ' + JSON.stringify(success));
            }
        },
        (error)=>{
            console.log('Error loading friends : ' + JSON.stringify(error));
        });


    });
  }
}

我的提供商:

import {Injectable, Inject} from 'angular2/core';
import {Http} from 'angular2/http';

/*
  Generated class for the FacebookFriends provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class FacebookFriends {
  constructor(@Inject(Http) http) {
    this.http = http;
    this.data = null;
  }

  load() {
    if (this.data) {
      // already loaded data
      return Promise.resolve(this.data);
    }
    // don't have the data yet
    return new Promise(resolve => {
      // We're using Angular Http provider to request the data,
      // then on the response it'll map the JSON data to a parsed JS object.
      // Next we process the data and resolve the promise with the new data.
       var headers = new Headers();
                            // headers.append('Content-Type', 'application/json');
                            headers.append('Content-Type', 'application/x-www-form-urlencoded');
                            this.http.post(
                                'http://192.168.1.45:3000/testrestapi',
                                {headers: headers}
                            ).map((res => res.json())
        .subscribe(data => {
          // we've got back the raw data, now generate the core schedule data
          // and save the data for later reference
          this.data = data;
      console.log('Friends Provider was a success!');
      console.log(JSON.stringify(data));
          resolve(this.data);
        },
    (err)=>{
        console.log('Error in Friends Provider!');
    },
    ()=>{
           console.log('Friends Provider network call has ended!');
    });
    });
  }
}

我的页面

import {Page} from 'ionic-angular';
import {FacebookFriends} from '../../providers/facebook-friends/facebook-friends';

@Page({
  templateUrl: 'build/pages/page1/page1.html'
})
export class Page1 {

constructor(platform:Platform,facebookFriends:FacebookFriends) {
    this.rootPage = TabsPage;

    this.fb = facebookFriends;


  }

}

1 个答案:

答案 0 :(得分:0)

您应该使用具有Observable类型的属性的共享服务:

export class SharedService {
  dataReadyNotifier: Observer;
  dataReadyObservable: Observable;

  constructor() {
    this.dataReadyObservable = Observable.create((observer) => {
      this.dataReadyNotifier = observer;
    });
  }

  notifyDataReady(data) {
    this.dataReadyNotifier.next(data);
  }
}

当数据存在于promise回调中时,将调用该服务的notifyDataReady方法。

要收到通知,组件将以这种方式在服务上注册:

export class SomeComponent {
  constructor(private sharedService: SharedService) {
    this.sharedService..dataReadyObservable.subscribe((data) => {
      // Do something with data
    });
  }

  (...)
}