2

I'm new to angular and migrating a project from angularJS to angular. I'm having below issue with the existing flow.

1.authcomponent:

function FuncBasedOnLogin()
{  authServices.hasLoggedIn(dataService.dataModel.tenant).then(function (isLoggedIn) 
   {//Do something with response});   
}

2.authservice:

function hasLoggedIn(tenant){
    return restService.get(url).then(function (response) //This returns new promise
    { //Do something and return boolean response });

} 3.RestService:

function get(url) {
            return $http.get(url).then(handleSuccess, handleError);
        }

For http calls angularJS was using promises and now angular uses Observable by default. Hence I want to know if we can achieve this by observable way? I'm seeing when I replace then with subscribe in authservice, it's returning subscription which doesn't allow another subscribe down the chain.

I have tried converting toPromise() and achieved the same easily, but want to know if I can do the same using obervable? I have tried ShareReplay as below in authservice & subscribing once in authservice & once again on authcomponent:

let res = this._restService.get<any>(url).pipe(
      shareReplay(1)
    );

But the problem is it returns same response, but as you can see promise allows me to have modified response down the chain. I might be wrong. Can someone suggest a solution with example?

1 Answers1

2

If you want to chain observables together you can switchMap between them like

this._restService.get<any>(url).pipe(
  switchMap(res => this._restService.get<any>(`someUrl/${res.data}`)),
  switchMap(res2 => this._restService.get<any>(`someOtherUrl/${res2.data}`))
).subscribe(res3 => {
  // do stuff with res3
});

if the second one doesn't rely on the first you can fire them at the same time with forkJoin

forkJoin([
  this._restService.get<any>(url1),
  this._restService.get<any>(url2),
  this._restService.get<any>(url3)
]).subscribe(([res1, res2, res3]) => {
  // do stuff with reponses
});

if order is unimportant you can merge them

merge(
  this._restService.get<any>(url1),
  this._restService.get<any>(url2),
  this._restService.get<any>(url3)
).subscribe(res => {
  // res will fire 3 times when the calls finish
  // it will happen in order that they finish
});

There is also combineLatest, mergeMap, combineMap and more. Angular is built upon RxJs and learning it will make you a better Angular dev. You definitely was to use RxJs, converting observables to promises strips them of their RxJs superpowers and the ease in which you can transform them into a data stream that fits your needs.

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60