1. description
Whether using angularjs as the front-end or combining with ionic to develop mobile app, it needs to interact with the back-end, and angular provides httpModule module for us to use. Today we will show a specific process of encapsulation and use of http.
2. HttpModule introduction
Find the app.module.ts file
import { NgModule, ErrorHandler } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { LoginPage } from "../pages/login/login"; /** Introducing HttpClientModule module */ import { HttpClientModule } from "@angular/common/http"; import { RequestServiceProvider } from "../providers/request-service/request-service"; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; @NgModule({ declarations: [ MyApp, LoginPage, ], imports: [ BrowserModule, /** Import module */ HttpClientModule, IonicModule.forRoot(MyApp,{ tabsHideOnSubPages:'true', backButtonText:'' }) ], bootstrap: [IonicApp], entryComponents: [ MyApp, LoginPage, ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler}, RequestServiceProvider, ] }) export class AppModule {}
Just import HttpClientModule module according to your own project. I import other components without consideration.
3. Create service
ionic g provider RequestService
After execution, the following files will appear
4. Package services
/** Import http related */ import { HttpClient,HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import {Observable} from "rxjs"; /* Generated class for the RequestServiceProvider provider. See https://angular.io/guide/dependency-injection for more info on providers and Angular DI. */ @Injectable() export class RequestServiceProvider { /** When we talk about basic path extraction, we only need to modify it here when we configure ip and port */ //basePath:string='http://10.4.0.205:8081' reserveBasePath:string='http://10.6.254.110:8081' basePath=this.reserveBasePath; /** Encapsulate fixed header correlation */ private headers = new HttpHeaders({'Content-Type': 'application/json'}) // private headers = new HttpHeaders({'Access-Control-Allow-Origin':'*'}); /** Initialize http variables */ constructor(public http: HttpClient) { console.log('Hello RequestServiceProvider Provider'); } /** Four basic methods are provided for the outside world, just passing in uri and data */ get(req:any):Observable<any> { return this.http.get(this.basePath+req.uri,{headers:this.headers}); } post(req:any):Observable<any>{ return this.http.post(this.basePath+req.uri,req.data,{headers:this.headers}); } put(req:any):Observable<any>{ return this.http.put(this.basePath+req.uri,req.data,{headers:this.headers}); } delete(req:any):Observable<any>{ return this.http.delete(this.basePath+req.uri,{headers:this.headers}); } }
5. Import declaration encapsulation service
Find the app.module.ts file similar to the first one
import { NgModule, ErrorHandler } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { LoginPage } from "../pages/login/login"; /** Introducing HttpClientModule module */ import { HttpClientModule } from "@angular/common/http"; /** Import custom service */ import { RequestServiceProvider } from "../providers/request-service/request-service"; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; @NgModule({ declarations: [ MyApp, LoginPage, ], imports: [ BrowserModule, /** Import module */ HttpClientModule, IonicModule.forRoot(MyApp,{ tabsHideOnSubPages:'true', backButtonText:'' }) ], bootstrap: [IonicApp], entryComponents: [ MyApp, LoginPage, ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler}, /** Declaration service */ RequestServiceProvider, ] }) export class AppModule {}
6. Use of services
Find the ts file corresponding to your own page, as shown in the following code
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; /** Import declaration */ import {RequestServiceProvider} from "../../providers/request-service/request-service"; /** * Generated class for the LoginPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-login', templateUrl: 'login.html', }) export class LoginPage { title:string = 'Sign in' promptMessage:string = '' user={ username:'', password:'' } req={ login:{ uri:'/user/login' } } constructor(public navCtrl: NavController, public navParams: NavParams, /** Initialize service object */ private requestService:RequestServiceProvider) { } ionViewDidLoad() { console.log('ionViewDidLoad LoginPage'); } login(){ /** Call the post method, and the subscribe() method can start the request, send the call once, and send the call many times */ this.requestService.post({uri:this.req.login.uri,data:user}).subscribe((res:any)=>{ console.log(res); if (res.code == 0){ this.promptMessage = res.message; } else { this.promptMessage = res.message; } }, error1 => { alert(JSON.stringify(error1)) }); } }