美文网首页我爱编程Ionic FrameworkIonic
ionic 调用restful API services时全局错

ionic 调用restful API services时全局错

作者: caiyaming | 来源:发表于2018-06-23 10:14 被阅读6次

    往往我们的ionic程序需要调用API Service. 比如天气,地图等等。当这些API Service 不稳定或者不可访问时,我们可以通过在注册一个自定义的ErrorHandler, 来处理此类错误。


    1.   将自定义错误处理类作为provider,  也就是Service.   在终端使用命令: ionic g provider GlobalErrorHandler .  ionic generate 命令行定义可以参考此处

    2.     实现GlobalErrorHandler, 完整代码如下。

     import { ErrorHandler, Injectable } from '@angular/core';

    import { AlertController } from 'ionic-angular';

    @Injectable()

    export class GlobalErrorHandler extends ErrorHandler {

      constructor(public alertCtrl: AlertController) {

        super();

      }

      handleError(error: any): void {

         super.handleError(error);

        // IMPORTANT: Rethrow the error otherwise it gets swallowed

        if (error) {

          if (error.status === 0 && error.name === 'HttpErrorResponse' && error.statusText === 'Unknown Error') {

            this.showAlert(' 后台服务遇到了问题,目前正在修复中,请稍后访问,给您带来不便,深表歉意。');

            //It's better to add this to log file.

          }

        }

      }

      showAlert(subTitleText) {

        let alert = this.alertCtrl.create({

          title: '发生错误!',

          subTitle: subTitleText,

          buttons: ['确定']

        });

        alert.present();

      }

    }

    3.   在 \src\app\app.module.ts 中注册 GlobalErrorHandler  . 以下是代码片段, 请关注粗体部分。

    import { GlobalErrorHandler } from '../providers/global-error-handler/global-error-handler';

    @NgModule({

      declarations: [...],

      imports: [...],

      bootstrap: [IonicApp],

      entryComponents: [

        MyApp 

      ],

      providers: [

         {provide: ErrorHandler, useClass: GlobalErrorHandler},

          //  IMP. GlobalErrorHandler should be here, otherwise it would not be triggered.

         GlobalErrorHandler

      ]

    })

    export class AppModule {}

    这样的话,我们就在ionic程序中引入了全局错误处理。 一旦第三方的services 或者我们自己的service 发生错误不可访问时, 页面将会有Alert弹出。 如下图所示。

    相关文章

      网友评论

        本文标题:ionic 调用restful API services时全局错

        本文链接:https://www.haomeiwen.com/subject/hkpkyftx.html