Вложите вызовы httpClient и скажите, какой из них не удалось? - PullRequest
0 голосов
/ 28 мая 2020

У меня есть компонент, похожий на фрагмент псевдокода внизу.

Мне нужно изменить onDeployForTesting(), чтобы он вызывал myService.save() перед вызовом myService.deployForTesting(). Я изучал вложенные Observables и вложенные вызовы httpClient, но я никогда не могу сказать, какой Observable вышел из строя (если это так). Мне нужно знать это, чтобы продолжить установку уведомлений.

Вопрос

Как вложить два (или более) запроса httpClient и посмотреть, какой из них в цепочке не удался ( способом Rx JS)?

Что я пробовал

onSaveAndDeployForTesting() {
    this.myService
        .save(arg1)
        .pipe(
            concatMap(  // also tried: switchMap, mergeMap
                () => this.myService.deployForTesting(arg2),
            ),
        )
        .subscribe(
            console.info,
            console.error,  // this gives a very generic error with no pointer to which Observable actually failed
            console.info,
        );
}

Существующий код

class MyClass {
    // other code

    onSave() {
        this.myService.save(arg1)
            .subscribe(
                (data) => {
                    this.notificationService.set({
                        type: NotificationType.SUCCESS,
                        title: 'Success',
                        description: 'Lorem ipsum dolor sit amet',
                    });
                },
                (err) => {
                    if (err.errorCode === 409) {
                        this.notificationService.set({
                            type: NotificationType.WARNING,
                            title: 'Save Conflict',
                            description: 'Lorem ipsum dolor sit amet',
                        });
                    } else {
                        this.notificationService.set({
                            type: NotificationType.ERROR,
                            title: 'Error',
                            description: 'Lorem ipsum dolor sit amet',
                        });
                    }
                },
            );
    }

    onDeployForTesting(arg1) {
        this.myService.deployForTesting(arg1)
            .subscribe(
                (data) => {
                    if (data.status === 207) {
                        this.notificationService.set({
                            type: NotificationType.WARNING,
                            title: 'Unable to deploy configuration',
                            description: 'Lorem ipsum dolor sit amet',
                        });
                    } else {
                        this.notificationService.set({
                            type: NotificationType.SUCCESS,
                            title: 'Success',
                            description: 'Lorem ipsum dolor sit amet',
                        });
                    }
                },
                (err) => {
                    this.notificationService.set({
                        type: NotificationType.ERROR,
                        title: 'Error',
                        description: 'Lorem ipsum dolor sit amet',
                    });
                },
            );
    }
}

class MyService {
    // other code

    save(data) {
        return this.http.put('/my/save/url', data);
    }

    deployForTesting(data) {
        return this.http.post('/my/deploy/url', data);
    }
}

1 Ответ

4 голосов
/ 28 мая 2020

Вы можете использовать Rx JS catchError. Попробуйте следующее:

import { throwError, of, EMPTY } from 'rxjs';
import { catchError, concatMap } from 'rxjs/operators';

onSaveAndDeployForTesting() {
  this.myService.save(arg1).pipe(
    catchError(saveError => this.handleSaveError(saveError)),
    concatMap(() => this.myService.deployForTesting(arg2).pipe(
      catchError(deployError => this.handleDeployError(deployError))
    ))
  )
  .subscribe(
    console.info,
    console.error,
    console.info,
  );
}

handleSaveError(error) {
  // handle error from `save()` call
  return EMPTY;      // also `throwError()` or `of()`
}

handleDeployError(error) {
  // handle error from `deployForTesting()` call
  return EMPTY;      // also `throwError()` or `of()`
}

Не забудьте вернуть наблюдаемое из catchError.

...