问题
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