我正在创建一个服务,该服务是对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))
);
}
效果
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)
问题出在这一行:
map((data: People) => of(new fromPeopleActions.PeopleCreateSuccess({ people: data }))),
您返回的Observable会发出操作而不是操作,所以它应该是这样的:
map((data: People) => new fromPeopleActions.PeopleCreateSuccess({ people: data })),