3

我目前正在用 Vuejs 开发一个 webapp。我创建了一个可以全局访问的 Mixin,它处理对我的 api 的任何请求:

export default {

  data() {
    return {
      apiURL: 'http://example.com/api',
      timeout: 10000,
    };
  },

  methods: {

    callAPI(method, url, body) {
      this.$http({
        url: this.apiURL + url,
        method,
        body,
        timeout: this.timeout,
      })
      .then((response) =>
        response,
      (response) => {
        if (response.data.error) {
            this.error = response.data.error;
        } else {
          this.error = 'We can\'t connect to the server. Please try again in a few minutes.';
        }
        return response;
      });
      // return 'test';
    },

  },

};

现在,在我的一些组件中,我调用了 api 函数:

const api_response = this.callAPI('POST', '/auth', credentials);
alert (api_response);

它工作正常,但有一件事没有按预期工作。我希望我的api_response常数具有的价值,response但它总是undefined。所以每次我收到这个警报时undefined。这怎么可能?当我取消注释return 'test'它的行时:我收到了一个警报test,但它似乎在该this.$http部分中不起作用......

4

1 回答 1

1

callAPI没有return声明,所以它返回undefined。如果它返回你的$http电话,它仍然不会给你response,但会是aPromise,所以你会想做类似的事情

let api_response;
this.callAPI('POST', '/auth', credentials).then((response) => api_response = response);
于 2016-09-11T12:45:57.157 回答