Http Interceptor Angular 4

旧街凉风 提交于 2019-12-23 04:48:23

问题


I'm getting an error in my Typescript file that uses the Angular 4 framework. intelliJ IDE is not able to recognize the any datatype for HttpRequest.

Here is the code:

import {Component, Injectable, OnInit} from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import {ActivatedRoute, Router} from "@angular/router";
import {
  HttpClient, HttpErrorResponse, HttpEvent, HttpHandler, HttpHeaders, HttpRequest,
  HttpResponse, HttpInterceptor, HttpEventType} from "@angular/common/http";
import * as $ from "jquery";

@Injectable()
export class Service {

public getNames() {

   intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
       if (request.responseType == 'json') {
       request = request.clone({ responseType: 'text' });

       return next.handle(req).map(response => {
         if (response instanceof HttpResponse) {
         response = response.clone<any>({ body: JSON.parse(response.body) });
      }

      return response;
    });
  }
}

From the following GitHub website: https://github.com/angular/angular/issues/18396#issuecomment-349403045

I've checked that I'm importing '@angular/common/http' and that my Typescript version is up-to-date (I have version 2.6.2).

Does anyone know how to fix this? Any suggestions would be greatly appreciated.

Thank you.


回答1:


The right way to use interceptors is this:

import {
  Injectable,
} from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import {
  Observable
} from 'rxjs/Observable';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  constructor() {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (request.responseType == 'json') {
      request = request.clone({ responseType: 'text' });
    }

    return next.handle(request).map(// your code here)
  }
}

find the difference in your code.



来源:https://stackoverflow.com/questions/47661972/http-interceptor-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!