通过 HttpInterceptor Angular 5 添加标头

Boa*_*rty 1 angular5

我想添加标头以从 Angular 5 Web 应用程序发布请求。我创建了以下 Injectable 类,在我的应用程序模块中注册:

@Injectable()
    export class headerInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {    
        // Clone the request to add the new header         
        const authReq = req.clone({
          headers: new HttpHeaders({
            'Content-Type':  'application/json; charset=utf-8',        
          })
        });        
        return next.handle(authReq);


      }
    }
Run Code Online (Sandbox Code Playgroud)

我有网络通信服务,并且我添加了如下的正文参数。

@Injectable()
export class NetworkService {

  Root:string = 'some valid url';
  results:Object[];
  loading:boolean;

  // inject Http client to our client service.
  constructor(private httpClient: HttpClient ) {

  }



  login(loginParams : URLSearchParams){    
    let baseURL = `${this.Root}/login`;                    
    this.httpClient.post(baseURL, JSON.stringify({'UserName':'123','Password':'123'} ))
    .subscribe(data => {
        console.log();
    },
    err => {
          console.log('Error: ' + err.error);
      });
Run Code Online (Sandbox Code Playgroud)

当我在 headerInterceptor 类中的 clone 方法之后放置断点时,我可以看到请求正文。问题是当我在 Chrome 中切换到网络选项卡时,出现 405 错误并且我看不到正文和新标题。当我返回原始请求“req”时,正文发送正常,但当然没有新的标头。

Sra*_*van 5

应用模块,

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { headerInterceptor } from './httpinterceptor'
Run Code Online (Sandbox Code Playgroud)

将其添加到提供者,

providers: [
{
    provide: HTTP_INTERCEPTORS,
    useClass: headerInterceptor,
    multi: true
}
],
Run Code Online (Sandbox Code Playgroud)

现在把intereptor改成,我已经改了headers添加方式

@Injectable()
    export class headerInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authReq = req.clone({
              headers:req.headers.set("Content-Type", "application/json; charset=utf-8")
        });
        return next.handle(authReq);
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用setHeaders

@Injectable()
export class headerInterceptor implements HttpInterceptor {
  constructor() {}
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {y
    req = req.clone({
      setHeaders: {
        "Content-Type": "application/json; charset=utf-8"
      }
    });
    return next.handle(req);
  }
}
Run Code Online (Sandbox Code Playgroud)