Search code examples
angularionic-frameworkrxjsionic4

Converting rest api promises requests to rxjs requests in angular ionic


I am migrating code of old project in to new project. In old project I am using promises for rest api requests, however, in new project I am using rxjs.

Sample of rest api request method in old project:

 function getRequest(path, customHeader) {
    var deferred = $q.defer();
    var options = createOptions(deferred);
    if (customHeader) {
      options.headers = jsonConcat(options.headers, customHeader);
    }

    if (!isOnline) {
      errorOccurred(null);
      deferred.reject();
      return deferred.promise;
    }
    var cachedData = serviceCache.getCachedNode(path);
    if (cachedData) {
      //console.log("Using cached data for request "+APP_CONSTANTS.GATEWAY.ENDPOINT+path);
      //console.log(cachedData);
      deferred.resolve(cachedData);
    } else {
      $http.get(APP_CONSTANTS.GATEWAY.ENDPOINT + path, options).then(
        function(data, status, headers, config) {
          if (serviceError(data)) {
            deferred.reject(data);
          } else {
            deferred.resolve(data);
            serviceCache.setCacheNode(path, data);
          }
        },
        function(data, status, headers, config) {
          errorOccurred(data);
          deferred.reject(data);
        }
      );
    }
    return deferred.promise;
  }

Sample of rest api request method in new project:

 getRequest(path, customHeader) {
   let options = this.createOptions();
   if (customHeader) {
     options.headers = this.jsonConcat(options.headers, customHeader);
   }

   if (!this.isOnline) {
     this.errorOccurred(null);
   }
   let cachedData = this.cacheService.getCachedNode(path);
   if (cachedData) {
     //console.log("Using cached data for request "+APP_CONSTANTS.GATEWAY.ENDPOINT+path);
     //console.log(cachedData);
     return cachedData;
   } else {
     return this.http
    .get(
      this.APP_CONSTANTS.getAppConstants().GATEWAY.ENDPOINT + path,
      options
    )
    .pipe(
      map(
        (data) => {
          if (this.serviceError(data)) {
            return;
          } else {
            this.cacheService.setCacheNode(path, data);
          }
        },
        (error) => {
          this.errorOccurred(error);
        }
      )
    );
   }
  }

I am bit confused about defer. What is the equivalent of defer, deferred.resolve(data); and deferred.reject(data); in rxjs? What should I add in sample cod eof my new app in place of defer or there is no need to add anything? If someone knows then please share your point of view. Thanks


Solution

  • $q is essentially an implementation of Promise and Angular 2+ version they switched to rxJs and it's all about observable. You can handle the observable as per your need and it's a stream of data.

    Some basic functions which you can take a look into that are switchMap, mergeMap, combineLatest etc.

    RXJS guide on Angular app