当我从API获得404响应时,我想初始化我的可观察对象



当我从API获得404响应时,我想初始化我的可观察对象我试过这个代码,但它不起作用

const urlParams = { email: this.email };
this.voicesProfileObservable$ = this.service.request<any>(
AVAILABLE_SERVICES.GET_USER_PROFILE_VOICES.ID,
{},
{ urlParams }
).pipe(
catchError((error) => {
this.voicesProfileObservable$ = Observable.of({
aboutSectionType: '',
aboutCustomizedDescription: '',
showSpacesFollowed: true,
showBadgesEarned: true,
showMobileNumber: true,
showOfficeNumber: false,
showEmail: true,
showSlackHandle: false,
video: {},
socialLinks: [],
personalLinks: [],
});
return throwError(error);
}))

因为你设置了这个。voicesProfileObservable$ more次。第一次是在你定义并声明它为一个可观察对象时,第二次是在catchError()中。

您应该捕获错误,并返回of(…data)而不抛出错误。

catchError(_ => of({
aboutSectionType: '',
aboutCustomizedDescription: '',
showSpacesFollowed: true,
showBadgesEarned: true,
showMobileNumber: true,
showOfficeNumber: false,
showEmail: true,
showSlackHandle: false,
video: {},
socialLinks: [],
personalLinks: [],
})

可以这样试试:

this.voicesProfileObservable$ = this.service.request<any>(
AVAILABLE_SERVICES.GET_USER_PROFILE_VOICES.ID,
{},
{ urlParams }
).pipe(
catchError((error) => {
return of({
aboutSectionType: '',
aboutCustomizedDescription: '',
showSpacesFollowed: true,
showBadgesEarned: true,
showMobileNumber: true,
showOfficeNumber: false,
showEmail: true,
showSlackHandle: false,
video: {},
socialLinks: [],
personalLinks: [],
});
})
)

您应该直接在catchError回调中返回默认响应,以便将其传递给订阅者。

最新更新