首页 > 解决方案 > 拦截方法中不可见变量值-HTTP拦截器Angular

问题描述

我正在尝试使用 HTTP 拦截器在 HTTP 请求的标头中传递变量值。但它没有发生

我尝试将变量从 AppComponent 传递给服务。我可以看到变量值,但在 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()

应用模块

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 { }

标签: angularangular2-servicesangular4-httpclient

解决方案


根据文档,intercept 有一个返回类型Observable<HttpEvent<any>>,并且您没有在拦截函数中返回任何内容。您的拦截函数中还有一个语法错误(您已放置:但未指定返回类型)您可以:完全删除或指定返回类型Observable<HttpEvent<any>>,尽管最好指定返回类型以保持代码强类型。

您可以返回一个空的 observable 用于测试目的。

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  console.log("interceptetag : " + this.etag) 
  return new Observable<any>();
}

这是StackBlitz上的一个工作示例


推荐阅读