-1

i got a Angular components that in the init execute 2 funcions, one of them charge a array and the second one takes the values of thata array and execute a service.

The problem is that the second funcion execute before the first so the array is not charge and the second funcion returns error.

This is the code:

import { fromEvent, Subscription } from 'rxjs';
  ngOnInit(): void {
            this.getProducts();
            this.getLoans();
        }

getProducts() {
        this.clientService.getClientProducts(this.clientId).subscribe(
            (res) => {
                if (res.success) {
                    this.products = res.data;
                    console.log('Obtiene productos');
                    console.log(this.products);
                } 
            }
        );
    }


    getLoans() {
        console.log('Obtiene loans');
        console.log(this.products);
        this.products.forEach((element) => {
            if (element.id == '4') {
                this.clientService.getClientLoan(this.clientId).subscribe(
                    (res) => {
                        if (res.success) {
                            this.loans.push(res.data);
                        } else {
                            this.hasErrorOnLoans = true;
                        }
                    },
                );
            }
        });
    }

and the console log, can we see that the log that the first functions execute before:

console log

Sorry for my inglish! and thanks.

Excedd
  • 1
  • 3
  • Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – R. Richards Apr 29 '21 at 13:47
  • I would suggest to call the second method when the first method has received a response inside subscribe callback – Mir entafaz Ali Apr 29 '21 at 13:48
  • You need to call getLoans inside getProducts subscription, and a little research on asynchronous programming. – Berk Kurkcuoglu Apr 29 '21 at 13:49

3 Answers3

1

The problem is that you have not synchronize the two asynchronous call. The simplest thing you can do is call the second one function when the first one get the data, in this way

getProducts() {
        this.clientService.getClientProducts(this.clientId).subscribe(
            (res) => {
                if (res.success) {
                    this.products = res.data;
                    this.getLoans();
                } 
            }
        );
    }

In this way when you call getLoans() function products array is filled.

FedG
  • 1,218
  • 1
  • 5
  • 14
  • Yes, solve this with the solution!. anyway i need read something about asynchronous progrraming – Excedd Apr 30 '21 at 04:06
  • Yes, when you do an api call in angular 2, it is an asynchronous one. Anyway if my answer it was useful, please mark it like accepted answer or mark it as useful. Thanks – FedG Apr 30 '21 at 07:56
0

Hope below snippet helps

import { fromEvent, Subscription } from 'rxjs';
import { map } from 'rxjs/operators';

 ngOnInit(): void {
        getProducts().pipe(
        map(products => products.filter(p => p.id == '4')),
        tap(filteredProducts => {
          getLoans(filteredProducts)
        })
         ).subscribe();
    }

getProducts(): Observable<ClientProduct> {
      return this.clientService.getClientProducts(this.clientId);
}


getLoans(filteredProducts) {
    filteredProducts.forEach((element) => {
      this.clientService.getClientLoan(this.clientId).subscribe((res) => {
          if (res.success) {
              this.loans.push(res.data);
          } else {
              this.hasErrorOnLoans = true;
          }
      });
  });
}
Jacob
  • 1
  • 1
-2

I think you are looking for a solution like below.

Solution 1

async ngOnInit() {
  await this.firstFunction();
  await this.secondFunction();
}

Solution 2

Just using the switchMap operator or such things of Observable.

Liu Zhang
  • 1,808
  • 19
  • 31