typescript 类型“void”不可分配给类型“ObservableInput<{}>”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43115390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:40:04  来源:igfitidea点击:

Type 'void' is not assignable to type 'ObservableInput<{}>'

typescriptangular4

提问by eestein

This error started to pop up after I migrated to TS 2.2.2, so I'm assuming that's the problem... The code did not stop working, but now I receive that error and I tried a few things like returning an empty observable, catching the re-thrown exception and returning an object, nothing seemed to work. Why is this happening now? Shouldn't it understand I'm re-throwing the exception and not expect a return? Am I misreading the error?

这个错误在我迁移到 TS 2.2.2 后开始弹出,所以我假设这就是问题所在......代码没有停止工作,但现在我收到了这个错误,我尝试了一些事情,比如返回一个空的 observable ,捕获重新抛出的异常并返回一个对象,似乎没有任何效果。为什么现在会发生这种情况?难道它不应该明白我正在重新抛出异常而不期望返回吗?我误读了错误吗?

This is the complete error description:

这是完整的错误描述:

enter image description here

在此处输入图片说明

Here's the complete code:

这是完整的代码:

return request
    .map((res: Response) => res.json())
    .catch((error: any) => {
        // todo: log?

        if (error.status == 500) {
            this.alertService.showError(error.statusText);
        } else if (error.status == 588) {
            this.alertService.showAlert(error.statusText);
        }

        Observable.throw(error.statusText);
    });

I tried returning the Observable, but my wrapper method expects a return of type T, which is the return of my deserialized request (map(...)). If I do return the throwthis is the error I get:

我尝试返回 Observable,但我的包装器方法期望返回 type T,这是我的反序列化请求 ( map(...))的返回。如果我确实返回,throw这是我得到的错误:

[ts] Type 'Observable' is not assignable to type 'T'

[ts] 类型 'Observable' 不可分配给类型 'T'

I'm using:

我正在使用:

  • Angular4
  • Typescript 2.2.2
  • 角4
  • 打字稿 2.2.2

回答by Bougarfaoui El houcine

you have to return the Observable

你必须返回 Observable

 return request
    .map((res: Response) => res.json())
    .catch((error: any) => {
        // todo: log?

        if (error.status == 500) {
            this.alertService.showError(error.statusText);
        } else if (error.status == 588) {
            this.alertService.showAlert(error.statusText);
        }

        return Observable.throw(error.statusText);
    });

回答by Prashant M Bhavsar

Sometimes when you call catch without using arrow function like below

有时,当您在不使用箭头函数的情况下调用 catch 时,如下所示

getUserList() {
    return this.http.get(this.constURL + '/api/url/here', this.headerOptions)
    .catch(this.handleError);
}

handleError(error: Response) {
    if (error.status == 500) {      
      this.router.navigate(['/login']);
    } else {
      return Observable.throw(error);
    }
}

then it gives error of

然后它给出了错误

ERROR TypeError: Cannot read property 'navigate' of undefined not getting this

错误类型错误:无法读取未定义的属性“导航”没有得到这个

Because in handleError function this object is not accessible..if you console this.router then you will get undefined.. so this object not working and not getting router all available methods

因为在 handleError 函数中,这个对象是不可访问的。

So you have to use arrow function here like below

所以你必须在这里使用箭头函数,如下所示

getUserList() {
    return this.http.get(this.constURL + '/api/url/here', this.headerOptions)
    .catch(error => { 
      return this.handleError(error);
    });
}

handleError(error: Response) {
    if (error.status == 500) {      
      this.router.navigate(['/login']);
    } else {
      return Observable.throw(error);
    }
}

Also if you have not mentioned return for handlerError function then it will throw error again like

此外,如果您没有提到 handlerError 函数的返回值,那么它会再次抛出错误,例如

Argument of type '(error: any) => void' is not assignable to parameter of type

'(error: any) => void' 类型的参数不可分配给类型参数

So its necessary to type return for handlerError function.

所以有必要为 handlerError 函数输入 return 。

Check herefor in detail.He has explained code very well with all possible errors and solution of that..worked for me

在这里为detail.He解释代码非常好,所有可能的错误和解决方案的that..worked我

回答by Josh Dando

This is an answer for angular 6 with RXJS 6. In your request function, it would look similar to this. Note that catchhas been replaced with catchErrorand Observable.throwis now throwError. Also in RXJS 6 we use pipe to join together a sequence of function we wish to perform instead of the dot chaining previously.

这是 RXJS 6 的 angular 6 答案。在您的请求函数中,它看起来与此类似。请注意,catch已替换为catchErrorObservable.throw现在是throwError。同样在 RXJS 6 中,我们使用管道将我们希望执行的一系列功能连接在一起,而不是之前的点链接。

//In your service

getData(url: string): Observable<any> {
    let options = this.getHTTPOptions();
    return this.http.get<any>(url, options).pipe(
          catchError( (err: any, caught: Observable<any>) => { return 
        throwError(this.generalErrorHandler(err, caught)) } ) );
}

Then you can have an error handler. The key is to specify the keyword returnin both the catchErrorfunction above and return the error in the handler. The arrow ( =>) allows you to pass the context of the calling function into the error handler which means you can do cool things such as this.router.navigate(['someroute']);(If you have the router imported in your service)

然后你可以有一个错误处理程序。关键是returncatchError上面的函数中指定关键字并在处理程序中返回错误。箭头 ( =>) 允许您将调用函数的上下文传递给错误处理程序,这意味着您可以做一些很酷的事情,例如this.router.navigate(['someroute']);(如果您的服务中导入了路由器)

//In your service

  generalErrorHandler(error: any, caught: Observable<any>): Observable<any> {
    console.log('error caught: ', error);
    if( error.error.status == "INVALID_TOKEN" || error.error.status == "MAX_TOKEN_ISSUE_REACHED"){
      console.log('token has expired');
      this.logout();
      return error;
    }
    return error;
  }

Some key imports to get this to work:

一些关键的导入来让它工作:

//Imports for the service

import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Http, Response } from '@angular/http';
import { catchError, map } from 'rxjs/operators';
import { Observable, throwError, of} from 'rxjs';

And lastly to subscribe to the request to get your data:

最后订阅获取数据的请求:

//In your component, don't forget to import your service

let response$ = this.someService.getData('url here');
response$.subscribe( 
    data => { console.log('do stuff to data here', data); },
    err => { console.log("couldn't get data, maybe show error to user"); },
    () => { console.log('function that is called upon finish'); }
);