Ionic HTTP request

Ionic HTTP request

Ionic http requests thing really makes me a little bit blinded, because with a token verification request needs, but they have is a white, first contact with Ionic, did not know how to achieve, try to write, it really easy a little success, record it.

Use Tools

First, create a file folder at the same level app providers, http requests used to store tools.
Create a folder at http providers folder, http folder, create a file http.ts.
Tools reads as follows:

import { HttpClient, HttpResponse } from '@angular/common/http';
import { AppConfig } from './../../app/app.config';

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

/*
  Generated class for the HttpProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class HttpProvider {

  private baseServerUrl = 'http://localhost'  //这个地方是请求的baseUrl

  constructor(public httpClient: HttpClient) {
    //console.log('Hello HttpProvider Provider');
  }

  /**
   * post请求
   * @param url 相对路径
   * @param params 参数
   */
  public post(url, params:any):Observable<any> {
    //console.log("此时token:",AppConfig.token)
    return this.httpClient.post(this.baseServerUrl + url,params,{
      headers:{
        'Content-Type': 'application/json',
        'X-Access-Token': AppConfig.token,
        'Request-Origin': 'app'
      }
    })
  }

  /**
   * get方法
   * @param url 相对路径
   * @param params 参数
   */
  public get(url,params:any):Observable<any>{
    //console.log("此时token:",AppConfig.token)
    return this.httpClient.get(this.baseServerUrl + url,{
      headers:{
        'Content-Type': 'application/json',
        'X-Access-Token': '' + AppConfig.token,
        'Request-Origin': 'app'
      },
      params:params
    })
  }

}

Create a file stored token of

Because we need to be authenticated, that is, when the request needs to carry token, token So I created a file used to store return after a successful login.
App.config.ts create a file in the app directory, file reads as follows:

export class AppConfig{
  public static token:string = '';
}

After a successful login, the token into the value inside, and then go back the next carry token token requesting data on the take from here.

Inject dependencies

Injection in the various dependencies file app.module.ts

import { HttpProvider } from '../providers/http/http';
import { HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';

injection

  imports: [
    ···
    HttpClientModule,
  ],

injection

providers: [
    ···
    HttpProvider,
  ],

use

In page requires http request, import packages

import {HttpProvider} from './../../providers/http/http';
import { AppConfig } from './../app.config';

In the constructor dependency injection

constructor( private httpProvider: HttpProvider,) {}

http get requests

this.httpProvider.get('/getCheckCode',{}).subscribe((resp => {
    if (!resp.success) {
       return;
    }
    console.log("返回数据",resp);
    }), error => {
    console.error(error);
})

http post request

let pa= {
      'username': 'wjw',
      'password': 'wjw'
    }
console.log(pa)
this.httpProvider.post('/login',pa ).subscribe((resp: any) => {
    console.log('登录成功',resp);
    AppConfig.token = resp.result.token  // 登录成功的token存起来
    }, error => {
    console.log('登录失败');
})

In general it is like this.

Published 141 original articles · won praise 164 · views 70000 +

Guess you like

Origin blog.csdn.net/weixin_42776111/article/details/104939657