Quiero verificar una llamada api dentro de un observable que suscribiré en un componente. Como está escrito a continuación, quiero ejecutar mi observable de esta manera, pero no funciona. ¿Qué cambios debo hacer en este código para que funcione? Cada vez que trato de suscribirme a través de él, especialmente a través del escenario cuando someObservableWrittenInTheSameService regresa con un error 404, quiero devolver url2.
getfunction(submissionId: string ){ if (some condition) { this.someObservableWrittenInTheSameService(parameter).subscribe( (httpValue: any) => { let url = ''; if (httpValue.code === 200) { return this.http.get(url1); } }, err => { if (err.code === 404) { return this.http.get(url2); } } ) } let url3 return this.http.get(url3); }Luego se llama a esta función en un componente donde está suscrito. Pero cada vez que someObservableWrittenInTheSameService devuelve 404, la suscripción siempre falla y pasa al bloque de error en el componente.
iif para devolver un observable condicionalmente.switchMap para mapear de un observable a otro. Más información aquí .catchError para realizar el manejo de errores. Desde su cuerpo, puede devolver la solicitud HTTP o reenviar el error (usando throwError ) o incluso completar el observable (usando la constante EMPTY ) según sus requisitos.Prueba lo siguiente
import { Observable, EMPTY, iif, throwError } from 'rxjs'; import { switchMap, catchError } from 'rxjs/operators'; getfunction(submissionId: string): Observable<any> { // <-- observable must be returned here const obs1$ = this.someObservableWrittenInTheSameService(parameter).pipe( switchMap((httpValue: any) => iif( () => httpValue.code === 200, this.http.get(url1), EMPTY // <-- complete the observable if code is other than 200 ) ), catchError((error: any) => // <-- `catchError` operator *must* return an observable iif( () => error.code === 404, this.http.get(url2), throwError(error) // <-- you could also return `EMPTY` to complete the observable ) ) const obs2$ = this.http.get(url3); return iif( () => someCondition, obs1$, obs2$ ); } En este caso, se suscribiría a la función getFunction() donde se usa.
Por ej.
this.getFunction('some value').subscribe({ next: (value: any) => { }, error: (error: any) => { }, complete: () => { } });