【问题标题】:Converting rest api promises requests to rxjs requests in angular ionic将rest api promise请求转换为角度离子中的rxjs请求
【发布时间】:2023-04-05 15:54:01
【问题描述】:

我正在将旧项目的代码迁移到新项目中。在旧项目中,我使用 promise 来处理 api 请求,但是,在新项目中,我使用的是 rxjs。

旧项目中的rest api请求方法示例:

 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;
  }

新项目中的rest api请求方法示例:

 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);
        }
      )
    );
   }
  }

我对延迟有点困惑。 defer的等价物是什么,deferred.resolve(data);和 deferred.reject(data);在 rxjs 中?我应该在我的新应用程序的示例代码中添加什么来代替 defer 或者不需要添加任何东西?如果有人知道,请分享您的观点。谢谢

【问题讨论】:

    标签: angular ionic-framework rxjs ionic4


    【解决方案1】:

    $q 本质上是他们切换到rxJs 的 Promise 和 Angular 2+ 版本的实现,而这一切都与observable 有关。您可以根据需要处理 observable,它是一个数据流。

    您可以查看的一些基本功能是switchMapmergeMapcombineLatest 等。

    RXJS guide on Angular app

    【讨论】:

      猜你喜欢
      • 2020-04-02
      • 2021-07-07
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 2018-04-16
      相关资源
      最近更新 更多