Вызов API с RX JS не работает должным образом - PullRequest
0 голосов
/ 06 марта 2020

У меня есть компонент и сервис. Компонент вызывает функцию сервиса, которая создает вызов API. Когда вызов API завершен, я хочу вызвать другую функцию и передать результат вызова API. Технологии: angular, rx js, чванство

В компоненте:

of(this.customerService.getCustomerOverview(this.id)).subscribe((x)=>{
      console.log(x);
      this.getResultValues(x);
    });

В обслуживании:

getCustomerOverview(id) {
    this.localSubscriptions.push(this.apiClient.getCustomer(id, '').subscribe(result => {
      console.log(result);
      return result;
    },
      (error: any) => {

      }));
  }

Ошибка: The this.getResultValues (Икс); вызывается до завершения вызова API, и результат возвращается к вызывающей функции.

Спасибо за помощь!

1 Ответ

0 голосов
/ 06 марта 2020

На вашем месте я бы сделал:

// service
import { BehaviorSubject } from 'rxjs';
....
public customerCache$: BehaviorSubject<any> = new BehaviorSubject(null);
getCustomerOverview(id) {
  return this.apiClient.getCustomer(id, '');
}
.....
// component
import { of } from 'rxjs;
import { switchMap, take } from 'rxjs/operators';
.....
this.customerService.customerCache$.pipe(
  // take(1) to kill the subscription after the subscribe, I am scared of an infinite loop because of the .next in the subscribe
  take(1),
  switchMap(cache => {
     // if the cache is truthy, great, use it
     if (cache) {
       return of(cache);
     } else {
       // else make an API call
       return this.customerService.getCustomerOverview(this.id);
     }
  }),
).subscribe(x => {
  // store x as the cache
  this.customerService.customerCache$.next(x);
  // make sure this console doesn't log infinitely
  console.log(x);
  this.getResultValues(x);
});

Нет необходимости отписываться от http вызовов в Angular, поскольку они конечны.

Теперь везде вам нужно прочитать значение из, вы можете прочитать его из кэша, аналогично этому. Я не фанат этого, потому что я бы использовал Ngrx. Продолжая этот путь, вы создаете код спагетти.

...