ember.js 如何在ember-cli 3.17中创建 AJAX 服务?

oyxsuwqo  于 2022-11-05  发布在  其他
关注(0)|答案(1)|浏览(156)

我最近试图将我的ember从ember-cli: 2.6.2升级到ember-cli: 3.17,我很难将我的 AJAX 服务实现与更新的ember-cli版本并行。我不是从头开始创建应用程序的人,这就是为什么我不知道为什么需要import { raw } from 'ic-ajax';。非常感谢任何帮助。
我收到的错误:Uncaught (in promise) TypeError: Cannot read property 'status' of undefined
这是我以前 AJAX 服务app/services/ajax.js

import Ember from 'ember';
import { raw } from 'ic-ajax';
import dasherizeObjectKeys from '../../utils/dasherize-object-keys';

const { inject, get, isEmpty } = Ember;

export default Ember.Service.extend({
  currentSession: inject.service(),

  request(url, method = 'GET', data = undefined, dataType = 'json') {
    data = JSON.stringify(dasherizeObjectKeys(data));
    return new Ember.RSVP.Promise((resolve, reject) => {
      const contentType = 'application/json';
      const token = this.get('currentSession.token');
      const headers= {
        'Authorization': `Token ${token}`,
        'X-Client-Platform': 'Web'
      };

      raw({ url, headers, data, type: method, dataType, contentType })
        .then((response) => this.handleSuccess(response, resolve))
        .catch((response) => this.handleError(response, reject));
    });
  },

  handleSuccess(response, resolve) {
    return resolve({
      status: response.jqXHR.status,
      response: response.response
    });
  },

  handleError(response, reject) {
    if (response.jqXHR.status === 401 && this.get('currentSession.isAuthenticated')) {
      this.get('currentSession').invalidate();
    }

    let error = get(response, 'jqXHR.responseJSON');
    if (isEmpty(error)) {
      const responseText = get(response, 'jqXHR.responseText');
      // FIXME: server should always return json, empty string is not json,
      // after backend is fixed, `JSON.parse` and try/catch for errors are not needed
      try {
        error = JSON.parse(responseText);
      } catch (e) {
        error = {
          errors: { detail: responseText }
        };
      }
    }

    error.status = response.jqXHR.status;
    reject(error);
  }
});

这是我的新 AJAX 服务app/services/request.js

import Service from '@ember/service';
import { Promise } from 'rsvp';
import fetch from 'fetch';
import dasherizeObjectKeys from '../../utils/dasherize-object-keys';

export default class RequestService extends Service {
  request(url, method = 'GET', data = undefined, dataType = 'json') {
    data = JSON.stringify(dasherizeObjectKeys(data));
    return new Promise((resolve, reject) => {
      const contentType = 'application/json';
      const token = this.get('currentSession.token');
      const headers= {
        'Authorization': `Token ${token}`,
        'X-Client-Platform': 'Web'
      };

      fetch({ url, headers, data, type: method, dataType, contentType })
        .then((raw) => this.handleSuccess(raw, resolve))
        .catch((raw) => this.handleError(raw, reject));
    })
  }

  handleSuccess(response, resolve) {
    return resolve({
      status: response.jqXHR.status,
      response: response.response
    });
  }

  handleError(response, reject) {
    if (response.jqXHR.status === 401 && this.get('currentSession.isAuthenticated')) {
      this.get('currentSession').invalidate();
    }

    let error = get(response, 'jqXHR.responseJSON');
    if (isEmpty(error)) {
      const responseText = get(response, 'jqXHR.responseText');
      // FIXME: server should always return json, empty string is not json,
      // after backend is fixed, `JSON.parse` and try/catch for errors are not needed
      try {
        error = JSON.parse(responseText);
      } catch (e) {
        error = {
          errors: { detail: responseText }
        };
      }
    }

    error.status = response.jqXHR.status;
    reject(error);
  }
}
pokxtpni

pokxtpni1#

当我从ic-ajax升级到fetch时,我使用了ember-fetch,它提供了对ic-ajax中的 AJAX 的直接替换:
使用前

var ajax = require('ic-ajax');

rsvpAjax: function (options) {
  return ajax.request(options.url, options);
}

之后

import ajax from 'ember-fetch/ajax';

rsvpAjax: function (options) {
  return ajax(options.url, options);
}

这让我了解了大部分内容,但是当从 AJAX 切换到fetch时,仍然有一些细微的语义变化需要处理,比如error.jqXHR.responseJSON已经不存在了。
之前:

if(error && error.jqXHR){
  var errorResponse = error.jqXHR.responseJSON || {};
  // do something with the errorResponse
}

之后:

if(error && typeof(error.json) === 'function'){
  return error.json().then((errorResponse) => {
    // do something with the error
  }
}

请注意,错误json是通过一个promise解决的,这很可能需要一些重构,因为 AJAX 版本没有。
正如你在上面的例子中看到的,jqXHR已经不存在了。我想你的状态问题也是类似的。如果你想看一个使用fetch的“ajax-service”的例子,请看我的ember-rest-client插件。它是一个超级简单的ember-fetch Package 器,我用它代替了ember-data。

相关问题