处理"handleError"和"extractData"私有方法的最佳实践



根据 Angular 文档,处理可观察的最佳方法如下所示。我的问题是,您能否建议我采用良好的编码实践,以避免在每个服务上一次又一次地使用handleErrorextractData私有方法?如何声明一次并在任何地方使用?

    getHeroes(): Observable<Hero[]> {
      return this.http.get(this.heroesUrl)
                      .map(this.extractData)
                      .catch(this.handleError);
    }
    private handleError (error: Response | any) {
      // In a real world app, you might use a remote logging infrastructure
      let errMsg: string;
      if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
      } else {
        errMsg = error.message ? error.message : error.toString();
      }
      console.error(errMsg);
      return Observable.throw(errMsg);
    }
  private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }

更新:

handle-observable-service.ts

import { Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
export abstract class HandleObservableService {
  //to handle error
  protected handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
  //to extract data
  protected extractData(res: Response) {
    let body = res.json();
    return body.data || {};
  }
}

身份验证数据.ts

import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { HandleObservableService } from "../utility-services/handle-observable-service";
@Injectable()
export class AuthenticationData extends HandleObservableService {
  authenticationEndPoint: string = "https://www.myk.com/admin/index.php?route=api/login&username=";
  constructor(public http: Http) {
    super();
  }
  //to login
  loginUser(username: string, password: string): Observable<any> {
    let headers = new Headers();
    headers.append('content-type', 'application/json');
    let body = '';
    let options = new RequestOptions({ headers: headers });
    let url = this.authenticationEndPoint + encodeURI(username) + '&password=' + encodeURI(password);
    return this.http.post(url, body, options)
      .map(this.extractData)
      .catch(this.handleError);
  }
}

登录.ts

import { Component } from '@angular/core';
import { NavController, NavParams, AlertController } from 'ionic-angular';
import { AuthenticationData } from "../../providers/authentication-data";
import { FormBuilder, Validators } from "@angular/forms";
import { Storage } from '@ionic/storage';
@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
  response: any;
  loginForm: any;
  constructor(public navCtrl: NavController, public navParams: NavParams, public authenticationData: AuthenticationData,
    public formBuilder: FormBuilder, public storage: Storage, public alertCtrl: AlertController) {
    this.loginForm = formBuilder.group({
      username: ['', Validators.required],
      password: ['', Validators.compose([Validators.minLength(4), Validators.required])]
    });
  }
  ionViewDidLoad() {
  }
  //to login
  loginUser(): void {
    if (this.loginForm.valid) {
      this.authenticationData.loginUser(this.loginForm.value.username, this.loginForm.value.password)
        .subscribe(data => {
          if (data.token != null && data.token != '') {
            this.storage.ready().then(() => {
              this.storage.set('token', data.token);
            });
            this.navCtrl.pop();
          } else {
            let alert = this.alertCtrl.create({
              title: 'Error',
              subTitle: 'User Name or Password is wrong',
              buttons: [{
                text: 'OK',
                handler: data => {
                }
              },]
            });
            alert.present();
          }
        },
        err => {
          console.log(err);
        },
        () => console.log('Complete')
        );
    }
  }
}

您可以创建基类,如下所示:

base.service.ts

import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
export abstract class BaseService {
   protected handleError (error: Response | any) {
      // In a real world app, you might use a remote logging infrastructure
      let errMsg: string;
      if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
      } else {
        errMsg = error.message ? error.message : error.toString();
      }
      console.error(errMsg);
      return Observable.throw(errMsg);
    }
  protected extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }
}

然后HeroService将扩展它:

英雄服务网

import { BaseService } from './base.service';
class HeroService extends BaseService {
  constructor(private http: Http) {
    super();
  }
  getHeroes(): Observable<Hero[]> {
    return this.http.get(this.heroesUrl)
                  .map(this.extractData)
                  .catch(this.handleError);
  }
}

相关内容

  • 没有找到相关文章