我的角度拦截器有问题。我有fetch
收到http请求。我想要,如果失败,我可以使用拦截器捕获错误。但是,当我发送get请求时,我的拦截器不起作用。拦截器看不到此请求。当我编辑get请求并使用HttpClient(this.http.get ...)时-一切顺利,一切正常。如何使用请求获取和拦截器?
@Injectable()
export class TestInterceptor implements HttpInterceptor {
constructor() {
console.log('constructor of interceptor');
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('interceptor work');
return next.handle(req);
}
}
@NgModule({
declarations: [
TestComponent
],
imports: [
SharedModule,
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TestInterceptor,
multi: true
},
]
})
export class TestModule {}
sendRequest(url: string, method = 'GET', body = null): Promise<any> {
let response: Response;
return fetch(url, {
method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: body ? JSON.stringify(body) : null
});
}
答案 0 :(得分:0)
在app.module.ts中添加内部提供程序
{
provide: HTTP_INTERCEPTORS,
useClass: ApiGatewayInterceptor,
multi: true,
}
创建公共服务:
import { Injectable,OnInit,Component } from '@angular/core';
import {Http,Headers,RequestOptions, RequestOptionsArgs,Response} from '@angular/http';
import { HttpEvent, HttpHeaders,HttpHandler, HttpInterceptor, HttpRequest, HttpClient,HttpParams,HttpResponse,HttpErrorResponse } from '@angular/common/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { environment } from '../../environments/environment';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';
@Injectable()
export class ApiGatewayInterceptor implements HttpInterceptor {
private queryParam: string = '';
constructor() { }
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
}
}
像这样使用apigateway调用:
formUrlParam(data) {
let queryString: string = '';
let httpParams = new HttpParams();
Object.keys(data).forEach(function (key) {
httpParams = httpParams.append(key, data[key]);
});
return httpParams;
}
post<T>(url, params) {
let httpParams = this.formUrlParam(params);
return new Promise((resolve, reject) => {
let result = this.http.post(url,params).subscribe(
(response) => resolve(response),
(error) => resolve(error)
)
});
}
patch<T>(url, params) {
console.log(params);
let httpParams = this.formUrlParam(params);
return new Promise((resolve, reject) => {
let result = this.http.patch(url,params).subscribe(
(response) => resolve(response),
(error) => resolve(error)
)
});
}
get<T>(url,params) {
let httpParams = this.formUrlParam(params);
return new Promise((resolve, reject) => {
let result = this.http.get(url,{params: httpParams }).subscribe(
(response) => resolve(response),
(error) => resolve(error)
)
});
}