类型&#39; Observable&lt; {}不能分配给&#39; Observable <httpevent <any>&gt;&#39;

时间:2017-11-07 10:41:48

标签: angular typescript rxjs

我想将角度4移植到角度5.我完成了从角度4到角度5的迁移,现在我的拦截器上有一个错误来刷新我的令牌。如果我有401错误,我使用此代码拦截所有请求并刷新我的令牌:

import { Observable } from 'rxjs/Observable';
import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { UserService } from "./user/services/user.service";
import { SpinnerService } from "angular-spinners";

@Injectable()
export class AngularInterceptor implements HttpInterceptor {
    public userService;
    public spinnerService;

    constructor(private injector: Injector) {
    }

    private applyCredentials = function (req) {
        return req.clone({
            headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('eb-app-token'))
        });
    };

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this.userService = this.injector.get(UserService);
        this.spinnerService = this.injector.get(SpinnerService);

        return next.handle(this.applyCredentials(req))
            /*.do(event => {

                if (event instanceof HttpResponse) {
                    console.log(event);
                }
            })*/
            .catch((res) => {
                console.log('Token refresh');
                if (res.status === 401 || res.status === 403) {
                    return this.userService.refreshToken().first().flatMap((data: any) => {
                        console.log(data.data);
                        if (data.data !== '') {
                            localStorage.removeItem('token');
                            localStorage.setItem('token', data.data);

                            this.userService.token = localStorage.getItem('token');
                            this.userService.isAuthenticated = true;
                        } else {
                            this.userService.logOut();

                            return Observable.throw(res);
                        }

                        return next.handle(this.applyCredentials(req));
                    });
                }
                else if (res.status === 500) {
                    this.spinnerService.hide('spinner');
                    this.spinnerService.hide('spinner-search');

                    this.userService.logOut();
                }

                return Observable.throw(res);
            });
    }
}

我有这个错误:

ERROR in src/app/app.interceptor.ts(25,9): error TS2322: Type 'Observable<{} | HttpProgressEvent | HttpSentEvent | HttpHeaderResponse | HttpResponse<any> | Http...' is not assignable to type 'Observable<HttpEvent<any>>'.
  Type '{} | HttpProgressEvent | HttpSentEvent | HttpHeaderResponse | HttpResponse<any> | HttpUserEvent<a...' is not assignable to type 'HttpEvent<any>'.
    Type '{}' is not assignable to type 'HttpEvent<any>'.
      Type '{}' is not assignable to type 'HttpUserEvent<any>'.
        Property 'type' is missing in type '{}'.

我试图修改不同的东西。我看了这篇文章Observable<{}> not assignable to type Observable<SomeType[]>,但我没有看到同样的问题...

第25行是:

return next.handle(this.applyCredentials(req))
  

更新

我修改了:

return next.handle(this.applyCredentials(req))

通过

return <any>next.handle(this.applyCredentials(req))

并导入:

import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';

1 个答案:

答案 0 :(得分:2)

您没有向句柄函数发送具有预期类型的​​对象。 您可以通过解析它来快速修复它,如

return next.handle(<any> this.applyCredentials(req))

但你真的应该检查你的退货类型,并确保它符合预期。

更新答案: 问题实际上是函数返回值,应该是Observable<HttpEvent<any>>。 简单的解决方法就是像这样转换为any

return <any> next.handle(this.applyCredentials(req))

但不保证它会起作用,因为它不属于正确的类。