Kristián Stroka
Kristián Stroka

Reputation: 730

Call multiple ajax and wait for result Angular2

I have problem with my Angular. I have this functions:

private callUserInfo(): any {
this.isLoading = true;

return this._ajaxService.getService('/system/ping')
  .map(
    result => {
      this.userId = 
         result.participant.substring(result.participant.indexOf('#'));
      this.isLoading = false;
    }
  )
  .catch(error => {
    return Observable.throw(error);
  });
}

public loadUserData(userName: string): any {
this.isLoading = true;

return this._ajaxService.getService('/User/' + userName)
.map(
  result => {
    const data = result[0];

    this.user = new User(
        data.id,
        data.contacts[0].email,
        data.name,
        data.surname,
        data.address.street,
        data.address.city,
        data.address.state,
        data.address.country,
        data.address.postCode,
        data.address.timeZone);

    this.isLoading = false;
})
.catch(error => {
  return Observable.throw(error);
});
}

public getUser(): any {

if (this.user == null) {
  this.callUserInfo().subscribe(() => {
    this.loadUserData(this.userId).subscribe(() => {
      return this.user;
    });
  });
} else {
  return this.user;
}
}

In my component I call this service functions like this (auth service is service with functions defined up):

constructor(private _auth: AuthService) {
    this.user = _auth.getUser();
  }

But it stills return null (because Ajax calls are not finished?) Can someone explain me, how to call this two calls (first is system/ping service and based on return (userId) I need to call second ajax call (/user/id). After this two calls I have defined user in my service and I can return it to other components. Can someone expllain me, what am i doing wrong, or how I can do it better? I´m using newest version of angular.

P.S. Get service is from my wrapper service:

getService(url: string): Observable<any> {
          return this.http
              .get(this.base + url, this.options)
              .map(this.extractData)
              .catch(this.handleError);
      }

Upvotes: 0

Views: 216

Answers (2)

Naman Kheterpal
Naman Kheterpal

Reputation: 1840

You are not returning anything in case this.user==null

Change your function as following:

userObservabel=new BehaviourSubject(null);
public getUser(): any {

  if (this.user == null) {
    this.callUserInfo().subscribe(() => {
     this.loadUserData(this.userId).subscribe(() => {
       this.userObservabel.next(this.user);
      });
    });
    return this.userObservabel.asObservable();
   } else {
    return this.userObservabel.asObservable();
   }
}

and then you need to subscribe it

constructor(private _auth: AuthService) {
  _auth.getUser().subscribe(user => this.user = user);
 }

Upvotes: 1

Sagar Kharab
Sagar Kharab

Reputation: 369

You need to call the second service in the subscribe or in the map method i.e. the Observable has returned a promise and that is resolved. Once that is resolved u should call your chained service.

A sample snipped from my POC might help you

    this._accountListService.getAccountsFromBE().subscribe(
        response => {
            this.response = response;
            this._accountListService.getAccountSorting().subscribe(
                response => {
                    this.acctSort = response;
                    if (response.prodCode) {
                        this._accountListService.getAccountOrder().subscribe(
                            response => {
                                this.acctOrder = response;
                                this.response = this.setAccountOrder(this.response);
                                this.response.sort(this.myComparator);
                                this.acctFlag = true;
                                if (this.prodDesc) {
                                    this.loader = false;
                                    this.accountDetl = this.response[0];
                                    this.accountDetl.entCdeDesc = this.prodDesc[this.accountDetl.entProdCatCde];
                                }
                            },
                            err => console.log(err)
                        );
                    }
                },
                err => console.log(err)
            );
        },
        err => console.log(err)
    );

Upvotes: 0

Related Questions