Search code examples
angularrestrxjs

I Would like One Http call Completed before the next in angular


here is my Http requests in getAllUserData() i would like this.getAnXSRfToken() to finish exe before proceeding with the http request;

  getAllUserData() {
    //get XSRF token
    this.getAnXSRfToken();
    return this.http
      .post<User[]>('http://localhost:8080/user/get-all-users-post', null, {
        observe: 'response',
        withCredentials: true,
      })
      .subscribe({
        next: (array) => {
          this.allUsersData.next(array.body);
        },
        error: (e) => {
          console.log(e);
        },
      });
  }

here is the this.getAnXSRfToken() method

  getAnXSRfToken() {
    return this.http
      .post<{
        parameterName: string;
        headerName: string;
        token: string;
      }>('http://localhost:8080/user/getXSRfToken', null)
      .subscribe({
        next: (tokenData) => {
          console.log('REQ --- token ---generated ');
          console.log(tokenData.token);
          this.XSRF_TOKEN.next(tokenData.token);
        },
        error: (e) => console.log(e),
      });
  }

Solution

  • Remove the subscribes and just return the observable, then you can use switchMap to switch from the XHR API call, to the other API call sequentially!

    getAllUserData() {
        //get XSRF token
        this.getAnXSRfToken().pipe(
            switchMap(() => {
                return this.http
                    .post<User[]>('http://localhost:8080/user/get-all-users-post', null, {
                        observe: 'response',
                        withCredentials: true,
                    }).pipe(//array parameter was missed out 
                        tap((array) => {
                            this.allUsersData.next(array.body);
                        })
                    )
            })
        ).subscribe();
    
    }
    
    getAnXSRfToken() {
        return this.http
            .post<{
                parameterName: string;
                headerName: string;
                token: string;
            }>('http://localhost:8080/user/getXSRfToken', null)
            .pipe(
                tap((tokenData) => {
                    console.log('REQ --- token ---generated ');
                    console.log(tokenData.token);
                    this.XSRF_TOKEN.next(tokenData.token);
                })
            );
    }