我正在尝试使用HTTP拦截器在HTTP请求的标头中传递变量值。但这没有发生
我尝试将变量从AppComponent传递到Service。我可以看到变量值,但是在Intercept方法的同一服务中,我无法
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import * as $ from 'jquery';
@Injectable({
providedIn:'root'
})
export class AppInterceptorService implements HttpInterceptor{
etag : string
headers : HttpHeaders
constructor() {}
getEtag(etag : string) {
if(etag) {
this.etag = etag;
console.log("Etag from Interceptor :"+ this.etag)
}
else {
this.etag = '*'
}
}
handleError(error : HttpErrorResponse) {
console.log("Error Occured")
return throwError(error)
}
intercept(req: HttpRequest<any>, next: HttpHandler,): Observable<HttpEvent<any>> {
console.log("interceptetag : " + this.etag)
if(req.method === "GET"){
this.headers = new HttpHeaders ({
'Content-Type' : 'application/json;odata=verbose',
'Accept' : 'application/json;odata=verbose',
'X-RequestDigest' : $("#__REQUESTDIGEST").val(),
'X-HTTP-Method': 'MERGE',
'IF-MATCH': "40",
})
}
if(req.method === "POST"){
console.log("Etag form POST :"+this.etag)
this.headers = new HttpHeaders ({
'Content-Type' : 'application/json;odata=verbose',
'Accept' : 'application/json;odata=verbose',
'X-RequestDigest' : $("#__REQUESTDIGEST").val(),
'X-HTTP-Method': 'MERGE',
'IF-MATCH': this.etag,
})
}
const clone = req.clone({'headers' : this.headers})
return next.handle(clone)
.pipe(
retry (1),
catchError(this.handleError)
)
}
}
单击按钮:(组件类)
update() {
console.log("ETag :" + this.etag) // "40"
this.appInterceptorService.getEtag(this.etag) // Here I'm passing "40" ro above service
this.sharepointService.PostReqNo(this.counter).subscribe()
AppModule
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule,FormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { SharePointService } from './services/sharepointservice.service';
import { AppInterceptorService } from './services/app-interceptor.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ReactiveFormsModule,
FormsModule,
HttpClientModule
],
providers: [SharePointService,
{'provide' : HTTP_INTERCEPTORS,
'useClass' : AppInterceptorService,
'multi' : true}],
bootstrap: [AppComponent]
})
export class AppModule { }
答案 0 :(得分:0)
根据documentation,拦截器的返回类型为Observable<HttpEvent<any>>
,并且您在拦截函数中未返回任何内容。拦截函数中还存在语法错误(您已放置:
但未指定返回类型)您可以完全删除:
或指定返回类型Observable<HttpEvent<any>>
,尽管它最好指定返回类型,以使代码保持强类型。
出于测试目的,您可以返回一个可观察的空值。
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("interceptetag : " + this.etag)
return new Observable<any>();
}
上的有效示例