使用httpheaers获取请求在Angular 7中不起作用

时间:2019-07-15 11:42:56

标签: angular

我正在使用用于设置或取消设置授权令牌的HttpHeaders,但出现了

之类的错误

“ OperatorFunction”类型的参数不能分配给“ OperatorFunction,响应”类型的参数

所以如何跳过或跳过更好的方法,因为某些时间标记为空

    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Token ' + token,
      })
    };

    const httpOptions1 = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
      })
    };


   let opt;
   if (token) {
     opt = httpOptions
   } else {
    opt = httpOptions1

   }


    return this.http.get<any>(this.mURL , opt)
      .pipe(map((response: Response) => {
        return response;
      }), catchError((error: Response) => {
        return throwError(error.status);
      }));

1 个答案:

答案 0 :(得分:1)

创建拦截器的最佳解决方案: 创建一个新文件:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any> , next: HttpHandler ): Observable<HttpEvent<any>> {
    const token = localStorage.getItem('token'); // or from wherever you like to get your token 
    if (token) {
      req = req.clone({
        headers : req.headers.set('authorization', 'Bearer ' + token)
      });
      req = req.clone({
        headers  : req.headers.set('Accept', 'application/json, text/plain, */*') // this for accepting the most of body requests 
      });
      return next.handle(req).pipe(
        map((event: HttpEvent<any>) => {
          if (event instanceof HttpResponse) {
           console.log('event --->>', event); // you can remove that line in production build stage 
          }
          return event;
        }
      ));
    } else {
      return next.handle(req);
    }
  }
}

并将拦截器插入到您的app.module.ts提供程序中

providers:[
   {
      provide: HTTP_INTERCEPTORS,
      useClass : AuthInterceptor,
      multi: true
    }]

它将在您提出的每个请求中添加令牌