Skip to content Skip to sidebar Skip to footer

Where To Add Rest Api Consuming Functionality In Ionic Framework 3.x?

It has been a while since I used ionic framework. Last time, I used it it was version 1 and therefore, every page that i created with ionic creator had a controller for it where I

Solution 1:

You need to create providers to request REST API. Posting example :

Your Provider(rest-api.ts)

import { Injectable } from'@angular/core';
import { Http,Headers} from'@angular/http';
import { Observable } from'rxjs/Observable';
import'rxjs/add/operator/map';
import'rxjs/add/operator/catch';
import'rxjs/add/operator/timeout';
import'rxjs/add/observable/throw';


@Injectable()
exportclassRestApiProvider {

  private apiUrl = 'Your server api url';

    constructor(public http: Http) {
    console.log('Hello RestApiProvider Provider');
    }

    Login(dataparam){
        let param = 'your data params';
        returnthis.http.get(this.apiUrl+param)
                    .timeout(30000)
            .map(res => res.json())
            .catch(this.handleError);
      }


      handleError(error: any) {
        let errorMsg = error.message || 'Network Error ! Try again later.';
        returnObservable.throw(errorMsg);
    }


}

Provider should be inject in (app.module.ts)

import { HttpModule,Http } from'@angular/http';
import { RestApiProvider } from'../providers/rest-api/rest-api';

@NgModule({
  declarations: [
    .....
  ],
  imports: [
  ........
    HttpModule,
    .......
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    ......
  ],
  providers: [
    ......
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    RestApiProvider,
    ......
  ]
})
export classAppModule {}

Also inject provider in the page from where you want to do HTTP request:mobile-login.ts

import { RestApiProvider } from'../../providers/rest-api/rest-api';
..........

@IonicPage()
@Component({
  selector: 'page-mobile-login',
  templateUrl: 'mobile-login.html',
})
exportclassMobileLoginPage {

  constructor(public navCtrl: NavController, 
    public navParams: NavParams,
    public restProvider: RestApiProvider,
    ) {
  }

yourfunction{
    this.restProvider.Login(your comma seprate data param)
    .subscribe(
            (data: any) => {
                console.log(data)                    
            },
            (err) => {
                      console.log(err);
                    }
    );
}

Above is working example for my Ionic 3 App.

Post a Comment for "Where To Add Rest Api Consuming Functionality In Ionic Framework 3.x?"