如何在相同的Observable中正确返回错误或响应?

问题描述 投票:0回答:1

我正在创建对json-server的请求的服务。该服务将在NGRX @Effects中调用。但是,此方法会创建一个人,但是在我需要检查此人是否已经存在才能创建此用户之前,我已经执行了以下操作:

后端服务

getPeople(id: string): Observable<People> {
    return this.httpClient.get<People>(this.SERVER_URL, {
        params: {
            id,
        },
    });
}

createPeople(people: People): Observable<People | HttpErrorResponse> {
    return this.getPeople(people._id).pipe(
        map((data) => {
            if (data) {
                return this.httpClient.post<People>(this.SERVER_URL, people);
            } else {
                throw new HttpErrorResponse({
                    status: 200,
                    statusText: 'THE USER ALREADY EXISTS IN THE DATABASE, SO THE REQUEST CANNOT BE PROCESSED FOR THE CREATION OF A NEW one.',
                });
            }
        }),
        catchError((error) => throwError(error))
    );
}

EFFECTS

import { Injectable } from '@angular/core';
import { Actions, Effect, ofType } from '@ngrx/effects';
import { switchMap, catchError, map, tap } from 'rxjs/operators';
import { of } from 'rxjs';

import { BackendService } from '@app/services/backend.service';
import { People } from '@shared/interfaces/people.interface';
import * as fromPeopleActions from './people.actions';

@Injectable()
export class PeopleEffects {
    constructor(private action$: Actions, private backend: BackendService) {}

    @Effect()
    create$ = this.action$.pipe(
        ofType(fromPeopleActions.ActionTypes.CREATE),
        switchMap(({ payload }) => {
            const { people } = payload;
            return this.backend.createPeople(people).pipe(
                map((data: People) => of(new fromPeopleActions.PeopleCreateSuccess({ people: data }))),
                catchError((error) => of(new fromPeopleActions.PeopleCreateFail({ error })))
            );
        })
    );
}

但是IDE告诉我以下error

Type 'Observable<People | Observable<People> | HttpErrorResponse>' is not assignable to type 'Observable<People | HttpErrorResponse>'.
  Type 'People | Observable<People> | HttpErrorResponse' is not assignable to type 'People | HttpErrorResponse'.
    Type 'Observable<People>' is not assignable to type 'People | HttpErrorResponse'.
      Type 'Observable<People>' is missing the following properties from type 'HttpErrorResponse': name, message, error, ok, and 5 more.ts(2322)
angular rxjs ngrx-effects
1个回答
0
投票

此行:

map((data: People) => of(new fromPeopleActions.PeopleCreateSuccess({ people: data }))),

您返回的Observable发出的是动作而不是动作,因此应该像这样:

map((data: People) => new fromPeopleActions.PeopleCreateSuccess({ people: data })),
© www.soinside.com 2019 - 2024. All rights reserved.