ionic3封装http服务

1、使用命令行创建服务

    ionic g provider httpSer

    报错信息:

    1)报错一

    Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)

    [HttpSerProvider -> HttpClient]: StaticInjectorError(Platform: core)[HttpSerProvider -> HttpClient]:

    NullInjectorError: No provider for HttpClient!

 

    原因:没有在app.module.ts中引入HttpClientModule

 

// http 服务请求
import { HttpClientModule } from '@angular/common/http';
import { HttpSerProvider } from '../providers/http-ser/http-ser';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    EventInfoModal,
    LoginPage,
    ContentPage,
    ListPage
  ],
  imports: [
    BrowserModule,
    VgCoreModule,
    VgControlsModule,
    VgOverlayPlayModule,
    VgBufferingModule,
    IonicModule.forRoot(MyApp),
    NgChartModule,
    HttpClientModule,
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    EventInfoModal,
    LoginPage,
    ContentPage,
    ListPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    HttpSerProvider,
    HttpClientModule,
  ]
})
export class AppModule {}

2、编写代码

    1)服务编码

 

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

/*
  Generated class for the HttpSerProvider provider.

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

  constructor(public http: HttpClient) {
    console.log('Hello HttpSerProvider Provider');
  }
  public post(url: string, params: any = null, successCallback, errorCallback): any {
    // 此处使用的post模式为非严格模式,如果要使用严格模式,请把参数放在第二个位置 覆盖null
    return this.http.post(url, null, {
      params: params
    }).subscribe((res: any) => {
      this.responseSuccess(res, function (msg) {
        if (successCallback) {
          successCallback(res, msg);
        }
      });
    }, err => {
      if (errorCallback) {
        errorCallback(err);
      }
    });
  }
  // get数据
  public get(url: string, params?: any): any {
    return this.http.get(url, params);
  }
  // 删除相关请求
  public delete(url: string, params?: any): any {
    return this.http.delete(url, params);
  }

  /**
   * 处理响应的事件
   * @param res
   * @param {Function} error
   */
  private responseSuccess(res: any, callback) {
    if (res.code !== '0') { // 失败
      if (res.msg) {
        callback({code: res.code, msg: res.msg});
      } else {
        const data = res.data;
        let errorMsg = '操作失败!';
        data.map(i => {
          errorMsg = i.errorMsg + '\n';
        });
        callback({code: res.code, msg: errorMsg});
      }
    } else {
      callback(res);
    }
  }

  /**
   * 处理请求失败事件
   * @param url
   * @param err
   */
  private requestFailed(url: string, err) {
    let msg = '请求发生异常';
    const status = err.status;
    if (status === 0) {
      msg = '请求失败,请求响应出错';
    } else if (status === 404) {
      msg = '请求失败,未找到请求地址';
    } else if (status === 500) {
      msg = '请求失败,服务器出错,请稍后再试';
    } else {
      msg = '未知错误,请检查网络';
    }
    return msg;

  }
}

      1)问题一、post请求报403

      原因:跨域,为使用代理,在ionic.config.json文件中配置代码

 

{
  "name": "app-video-ai",
  "app_id": "",
  "type": "ionic-angular",
  "integrations": {
    "cordova": {}
  },
  "proxies": [
    {
      "path": "/upms",
      "proxyUrl": "http://192.168.1.80:8082/upms"
    },
    {
      "path": "/api",
      "proxyUrl": "http://192.168.1.80:8889/api"
    }
  ]
}

2)问题二、post请求报404

原因:后台使用的是非严格模式的post模式,而前台默认使用的是严格模式

3)问题三、post请求报404

原因:路径配置缺失

  2)模块使用  

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ContentPage } from '../content/content';
import { ToastController } from 'ionic-angular';
import { HttpSerProvider } from './../../providers/http-ser/http-ser';
/**
 * Generated class for the LoginPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public toastCtrl: ToastController,
              public http: HttpSerProvider
  ) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
  }

  /**
   * 登录逻辑相关
   * @param {HTMLInputElement} username
   * @param {HTMLInputElement} password
   */
  logIn(username: HTMLInputElement, password: HTMLInputElement) {
    if (username.value.length == 0) {
      this.alertMsg('请输入账号');
    } else if (password.value.length == 0) {
      this.alertMsg('请输入密码');
    } else {
      const userinfo = {
        username: username.value,
        password: password.value,
        remember: true
      }
      const me = this;
      me.http.post('/upms/login',userinfo, function(res, msg){
        if (res.code === '0') {
          me.navCtrl.push(ContentPage, userinfo);
        } else {
          me.alertMsg(res.msg);
        }
      }, function(msg){
        me.alertMsg(msg);
      });
    }
  }

  /**
   * 弹出相关信息逻辑
   * @param {string} message
   */
  alertMsg(message: string) {
    const toast = this.toastCtrl.create({
      message: message,
      cssClass: 'toast-message', // 目前没用 添加的位置不是想要的
      position: 'top', // “top”,“middle”,“bottom”。
      duration: 3000
    });
    toast.present();
  }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值