HttpInterceptor具有可观察的拦截'在类型' AuthenticationInterceptor'不是>基本类型中的相同属性' HttpInterceptor'

时间:2018-06-13 16:31:42

标签: angular angular-http rxjs6

我不明白这段代码有什么问题 你能帮帮我吗?

import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';

import { Observable } from 'rxjs';
import { switchMap, map } from 'rxjs/operators';

import { AuthenticationSharedStorage } from '../storages/authentication.storage';
import { AuthenticationToken } from '../../models/authentication.model';

@Injectable()
export class AuthenticationInterceptor implements HttpInterceptor {

  constructor(private storage: AuthenticationSharedStorage) {}
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    this.storage.getData()
    .pipe(
      switchMap((data:AuthenticationToken )=> {
      if(data){
        const authToken = data.token;
        const authReq = req.clone({ setHeaders: { Authorization: authToken } });
        return next.handle(authReq);
      }
      return next.handle(req);
      })
    );
  }
}

完整的错误是:

  

财产拦截&#39;在类型&#39; AuthenticationInterceptor&#39;不是   可分配给基本类型中的相同属性&#39; HttpInterceptor&#39;。类型   &#39;(req:HttpRequest,next:HttpHandler)=&gt;空隙&#39;不可分配   键入&#39;(req:HttpRequest,next:HttpHandler)=&gt;   可观察到的&GT;&#39 ;.键入&#39; void&#39;不能分配给类型   &#39;可观察&GT;&#39 ;. 16:3

2 个答案:

答案 0 :(得分:1)

您需要从Observable<HttpEvent<any>>返回intercept - 目前尚未返回任何内容。假设this.storage.getData()返回一个(可能是真的,因为它有pipe())然后只是在它之前放回一个。

intercept(req: HttpRequest<any>, next: HttpHandler) {
  return this.storage.getData()
  //...
}

答案 1 :(得分:0)

我也有同样的错误,问题是项目和npm包的rxjs版本不同造成的。

我通过在项目中安装相同版本的 rxjs 来解决这个问题。