加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Angular 2中拦截HTTP响应

发布时间:2020-12-17 17:26:53 所属栏目:安全 来源:网络整理
导读:我正在使用RC6,我正试图弄清楚如何在整个应用程序中捕获HTTP错误 – 特别是auth错误. 有很多帖子描述了如何使用自定义类扩展Http类,但我不确定如何完全注册新类,因为语法随着最近的ngModule更改而改变. 这是类(添加了所有相关的导入): @Injectable()export
我正在使用RC6,我正试图弄清楚如何在整个应用程序中捕获HTTP错误 – 特别是auth错误.

有很多帖子描述了如何使用自定义类扩展Http类,但我不确定如何完全注册新类,因为语法随着最近的ngModule更改而改变.

这是类(添加了所有相关的导入):

@Injectable()
export class InterceptedHttp extends Http {

 constructor(backend: ConnectionBackend,defaultOptions: RequestOptions) {
  super( backend,defaultOptions);
 }

 request(url: string | Request,options?: RequestOptionsArgs): Observable<Response> {
  console.log('request...');
  return super.request(url,options);
 }

 get(url: string,options?: RequestOptionsArgs): Observable<Response> {
  console.log('get...');
  return super.get(url,options);
 }
}

我以为我可以在@ngModule的提供程序部分执行以下操作:

imports: [ HttpModule,... ],providers: [
    ... 

    InterceptedHttp,{provide: Http,useClass: InterceptedHttp },ConnectionBackend
 ],

但这只是让我失去了一堆模块错误:

ERROR in [default] C:/WebConnectionProjects/AlbumViewer/Web/src/app/app.module.ts:64:10
Argument of type '{ imports: (ModuleWithProviders | typeof BrowserModule)[]; declarations: (typeof AlbumList | type...' is not assignable to parameter of type 'NgModuleMetadataType'.
  Types of property 'providers' are incompatible.
  Type '(typeof ConnectionBackend | typeof Album | typeof Artist | typeof Track | typeof AppConfiguration...' is not assignable to type 'Provider[]'.
  Type 'typeof ConnectionBackend | typeof Album | typeof Artist | typeof Track | typeof AppConfiguration ...' is not assignable to type 'Provider'.
  Type 'typeof ConnectionBackend' is not assignable to type 'Provider'.
  Type 'typeof ConnectionBackend' is not assignable to type 'FactoryProvider'.
  Property 'provide' is missing in type 'typeof ConnectionBackend'.

删除添加的行,一切正常.

那么,我如何注册自定义Http类?

解决方法

我的方法不同.我创建了一个与内置Http交互的HTTPService类,而不是扩展Http.

@Injectable()
export class HttpService{
    constructor(private http:Http){}

    /** Wrapper for Http.get() that intercepts requests and responses */
    get(url:string,options?:RequestOptions):Observable<any>{

        //pre-screen the request (eg: to add authorization token)
        options = this.screenRequest(options);

        return this.http.get(url,options)
            .map(res => res.json()) //my back-end return a JSON. Unwrap it
            .do(res => this.screenResponse(res)) // intercept response
            .catch(res => this.handleError(res));// server returned error status
    }

    /** similar to the above; a wrapper for Http.post() */
    post(url:string,body:string,options?:RequestOptions):Observable<any>{}

    /** edits options before the request is made. Adds auth token to headers.*/
    screenOptions(options?:RequestOptions):RequestOptions{}

    /** Called with server's response. Saves auth token from the server */
    screenResponse(jsonResponse:any){}

    /** Called when server returns a 400-500 response code */
    handleError(response:Response){}        
}

所以我的代码从不直接调用Angular的Http.相反,我调用HttpService.get().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读