首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用rxjs的angular2 http中间件

使用rxjs的angular2 http中间件
EN

Stack Overflow用户
提问于 2016-08-30 08:43:30
回答 1查看 1.9K关注 0票数 2

我正在使用angular2,并且有一个ApiService...下面是完整的类。

代码语言:javascript
复制
import {Store} from '@ngrx/store';
import { Injectable } from '@angular/core';
import { Headers, RequestOptions, Http } from '@angular/http';
import {AppState} from '../app.store';
import { Observable } from 'rxjs/Observable';
import {AuthActions} from '../actions/AuthActions';

@Injectable()
export class ApiService {

  private currentState: AppState;

  constructor(
    private store: Store<AppState>,
    private http: Http
  ) {
    // get config once...
    store.subscribe((state:AppState) => {
      this.currentState = state;
    });
  }

  // PUBLIC

  /*
  --  POST
   */
  post(path:string, payload:Object) {

    let request = this.http.post(
      this.getEndpoint(path),
      JSON.stringify(payload),
      this.getHeaderOptions('post')
    );

    // DOESN'T WORK... fires http twice
    // this.responseMiddleware(request);

    return request;
  }

  /*
   --  GET
   */
  get(path:string) {

    let request = this.http.get(
      this.getEndpoint(path),
      this.getHeaderOptions('get')
    );

    return request;
  }

  /*
   --  DELETE
   */
  delete(path:string) {

    let request = this.http.delete(
      this.getEndpoint(path),
      this.getHeaderOptions('delete')
    );

    return request;

  }

  // PROCESS ALL REQUESTS LOOKING FOR BAD STUFF ??
  // HOW to subscribe without firing http 2x ??
  // private responseMiddleware(request:Observable<any>) {
  //   request.subscribe(
  //     (res) => {},
  //     (err) => {
  //       // catch error
  //       if(err.status === 401) {
  //         // unorthorised
  //         this.store.dispatch({type:AuthActions.AUTHENTICATE_DELETE});
  //       }
  //     },
  //     () => {}
  //   );
  // }

  // GET ENDPOINT FROM CONFIG FILE
  private getEndpoint(path:string) {
    if(!this.currentState.config.file.endpoint) {
      throw new Error('========= CONFIG NOT SET =========');
    }
    return this.currentState.config.file.endpoint + path;
  }

  // PUT TOGETHER CORRECT HEADER OBJECT BASED ON REQUEST TYPE
  private getHeaderOptions(type:string = 'get') {

    let headersObj:any = {
      'Accept'          : 'application/json',
      'X-Lc-Svc-Channel': 'lc-web-product'
    };

    switch(type) {
      case 'post':
        headersObj['Content-Type'] = 'application/json';
        break;
      default:
        break;
    }

    let token = this.currentState.auth.token;
    if(token) {
      headersObj.Authorization = token;
    }

    return new RequestOptions({ headers: new Headers(headersObj)});

  }
}

我想要做的是在每个请求上有某种类型的中间件来监听状态代码……但是我尝试的解决方案(订阅http observable)触发两次http请求。

我怎么才能做到这一点而不发生这种情况呢?

EN

回答 1

Stack Overflow用户

发布于 2016-08-31 05:53:54

对于任何感兴趣的人,我目前已经解决了这个购买链接到每个请求类型的catch。我相信有更好的方法...如果你能想到一个,我很想知道,但这是目前有效的。

代码语言:javascript
复制
get(path:string) {

  let request = this.http.get(
    this.getEndpoint(path),
    this.getHeaderOptions('get')
  ).catch((err:any) => {
    if(err.status === 401) {
      this.store.dispatch({type:AuthActions.AUTHENTICATE_DELETE});
      return Observable.of('Not authenticated');
    }
    return err;
  });

  return request;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39217234

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档