簡體   English   中英

Angular 6 RxJS6類型“ void”不能分配給類型“ ObservableInput <{}>”

[英]Angular 6 RxJS6 Type 'void' is not assignable to type 'ObservableInput<{}>'

我正在將代碼轉換為使用RxJS6語法來使用管道和地圖,但出現錯誤。

error TS2345: Argument of type '(error: any) => void' is not assignable to parameter of type '(err:
any, caught: Observable<void>) => ObservableInput<{}>'.
  Type 'void' is not assignable to type 'ObservableInput<{}>'.

現有的代碼工作正常,但是我遇到的問題是,在返回結果之前,必須調用其他方法。 因此,據我了解,使用管道和地圖將解決此問題。 這是我最初的代碼:

this._reportingService.GetProjectReportsData(data).subscribe(result => {
    if (result != null) {
        this.reportData = result;
    }

}, error => {
    this.ErrorMessage('Unable to load workbook ' + error.toString());
    this._reportingService.isLoading = false;
});

這是我嘗試轉換為使用管道和地圖的代碼:

我已經進口了其他進口品

import { Observable, of, throwError } from 'rxjs';
import { map, catchError, retry } from 'rxjs/operators';

並在方法中(已修改;刪除了this.error),請指導如何為errorMessage添加代碼:

this._reportingService.GetProjectReportsData(data).pipe(
    map(result => {
        if (result != null) {

  this.reportData = result;


        }
    }))
    .subscribe();

我的服務類別:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { map, tap, catchError } from 'rxjs/operators';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';


@Injectable({
    providedIn: 'root'
})
export class ReportingService extends BehaviorSubject<any[]>{

    constructor(private http: HttpClient) {

    super(null);
    }

    public GetProjectReportsData(data: any): Observable<any> {
        return this.http.post(this.GetProjectReportDataUrl, data)
            .pipe(map(res => <any[]>res))
            .pipe(catchError(this.handleError));
    }
    private handleError(error: any) {

        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        return Observable.throw(errMsg);
    }

}

根據我的說法,雙管道鏈接會產生問題。

嘗試這樣。

 public GetProjectReportsData(data: any): Observable<any> {
        return this.http.post(this.GetProjectReportDataUrl, data)
            .pipe(
               map(res => <any[]>res),
               catchError(this.handleError)
             );
    }

我認為問題是由於您缺少map運算符中的return語句。

import { of } from 'rxjs';

this._reportingService.GetProjectReportsData(data).pipe(
    map(result => {
        if (result != null) {
           return this.reportData = result;
        }
        return of(null);
    }))
    .subscribe();

也不確定為什么要使用此驗證(結果!= null)。 小心一點。

catchError返回observable:

import { of } from 'rxjs';

...
catchError(error => of(this.ErrorMessage('Unable to load workbook ' + error.toString()))
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM