如何在 ember-cli 3.17 中创建 ajax 服务?

How do you create an ajax service in ember-cli 3.17?

我最近正在尝试将我的 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);
  }
}

当我从 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 已通过承诺解决,该承诺很可能需要进行一些重构,因为 ajax 版本不需要。

如您在上例中所见,jqXHR 已不存在。我想你的状态问题是相似的。如果您想查看使用 fetch 的 "ajax-service" 示例,请参阅我的 ember-rest-client 插件。它是围绕 ember-fetch 的超级简单包装器,我使用它而不是使用 ember-data。