Do things in the background


#1

I am new to angular and angular2. Everytime my app opens a http calls need to be made to Facebook to get a list of Facebook friends. When the user opens the app I would like the app to open, but during this time in the background I would like to get make a http call to facebook to get the friends, so when the user gets to the section where they can view their friends the friends are already there and they do not need to wait. Is there a standard way of doing this (Http calls in the background)?If so may someone show a basic example please as I would think this is a common feature?

Cheers!


#2

Http calls are always done in the background (asynchronously is probably a better term here). In Ionic 2 if you wanted to immediately trigger a request when the app is opened, rather than waiting until the user gets to that page you should put it inside of:

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

});

in your app.js file. You’ll most likely want to create a provider that will handle fetching the data and then storing that data locally. Then when you get to the page where you want to display the friends, just grab it directly from the provider, rather than launching a Http request.

Of course, there’s no guarantee that the Http request will have finished by the time the user gets to the friends page, so you will need to make sure you handle that.


#3

Thanks for the reply. So say when the app goes to page1 I start the HTTP call to Facebook inside of my page1.js file. During this time the user goes to page2 and the previous HTTP call did not complete before coming to this page and the page2.js code starts. IS my page1.js code still running the background?


#4

You don’t run the code on a page, you do it in a provider, which can be imported into any of your pages. You will trigger the load from your app.js file which is not a page, it’s the root component so it will trigger the load right away.

The provider will do its own thing in the background, and you can access the provider from any of your pages (as long as you import it) to grab the data. You will just have to make sure the provider returns a promise or something since the data might not yet be available, the automatically generated provider Ionic uses is a good start, run:

ionic g provider FacebookFriends

and most of the work will already be done for you.


#5

Thanks for the information. I am testing it out now, but have trouble understanding how to handle if the information is yet not available. I have included here my app.js which calls the provider, the provider code which calls a HTTP endpoint and returns some data, and my page1.js. I have included inside of the app.js the provider and have called it. I then go to page1, but am unsure how to call the provider now without calling the laod method again which would call my server again if the data is not yet available. From my page1 how could I know if there has been a call already made and I am just waiting opposed to a call has HTTP call has yet not been made and I should make it?

My 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));
		});


    });
  }
}

My Provider:

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!');
	});
    });
  }
}

My page:

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;

    
  }

}