Estoy aprendiendo RxJS. Tengo 2 api, según los datos de la primera api, tengo que llamar a la segunda api y devolver el valor. Lo hice con el método subscribe() como este:
checkPermission(permissionName: string): Observable<boolean> { this.checkCompanySettingForPermission( this.pageLevelCompanySettingName ).subscribe(res => { const shouldCheck = res.Value; if (shouldCheck.toLowerCase() === "true") { this.hasPermission(permissionName).subscribe(res => { this.$permissionSub.next(res.permission); }); } else { this.$permissionSub.next(true); } }); return this.$permissionSub.asObservable(); } Quiero evitar el método subscribe() en otro método subscribe() . ¿Puedo hacerlo con cualquier operador de RxJS?
Lo probé con switchMap() también pero obtuve muchos errores de sintaxis. Por favor ayuda.
Puede lograrlo utilizando uno de los operadores de mapeo RxJS de orden superior, como: switchMap , mergeMap , concatMap , combine la source observable con la nueva.
Entonces, si vamos con switchMap o mergeMap en su caso, deberíamos devolver al final un nuevo observable para fusionarlo con el original checkCompanySettingForPermission .
Si la condición es verdadera, devolverá el observable this.hasPermission , de lo contrario devolverá un nuevo uso observable of la función con el valor que necesitamos pasar ( true en su caso).
Puedes intentar lo siguiente:
checkPermission(permissionName: string): Observable<boolean> { this.checkCompanySettingForPermission(this.pageLevelCompanySettingName) .pipe( switchMap(res => { const shouldCheck = res.Value; if (shouldCheck.toLowerCase() === 'true') { // switchMap to the new observable, then map it to return only the permission. return this.hasPermission(permissionName).pipe( tap(result => { // do some stuff with the result before mapping it to the `result.permission` }), map(result => result.permission) ); } else { // return observable of true, to be handled within subscribe. return of(true); } }) ) .subscribe(permission => this.$permissionSub.next(permission)); return this.$permissionSub.asObservable(); } Y si no usa this.$permissionSub en otro lugar, puede eliminarlo del método anterior y return this.checkCompanySettingForPermission(....) sin subscribe , luego puede llamar a este método en su componente de la siguiente manera:
// Example this.service.checkPermission(addPermission).subscribe((value) => { console.log(value) })Prueba este formato.
checkPermission(permissionName: string): Observable<boolean> { this.checkCompanySettingForPermission(this.pageLevelCompanySettingName) .pipe( map(res => res?.Value.toLowerCase() === 'true' ? this.hasPermission(permissionName).pipe( map(result => result.permission) ) : of(true) ), switchMap(ob => ob) ) .subscribe(permission => this.$permissionSub.next(permission)); return this.$permissionSub.asObservable(); }