3

I'm currently developing a webapp in Vuejs. I created a Mixin that I can access globally which handles any request to my 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';
    },

  },

};

Now, in some of my components I call the api function:

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

It works fine, but one thing doesn't work as expected. I expect my api_response constant to have the value of response but it is always undefined. So every time I got this alert with undefined. How is that possible? When I uncomment the return 'test' line it works: I got an alert with test, but it doesn't seem to work within the this.$http part...

4

1 に答える 1

1

ステートメントcallAPIがないreturnため、 が返されますundefined$http呼び出しが返された場合でも、 は返されませんがresponseになるため、次のようなことを行う必要があります。Promise

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