问题描述
使用Angular 4框架的Typescript文件出现错误. intelliJ IDE无法识别HttpRequest的任何数据类型.
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.
这是代码:
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;
});
}
}
来自以下GitHub网站: https://github.com/angular/angular/issues/18396#issuecomment-349403045
From the following GitHub website: https://github.com/angular/angular/issues/18396#issuecomment-349403045
我已经检查过我要导入"@ angular/common/http",并且我的Typescript版本是最新的(我的版本为2.6.2).
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.
谢谢.
推荐答案
使用拦截器的正确方法是:
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.
这篇关于Http拦截器Angular 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!