简体   繁体   中英

Ember.RSVP.Promise with AJAX call

Hi I'm trying to understand the way promises work along with Ajax calls. I want to send a simple Ajax call to a certain end point but I'm really confused with the code syntax. Here is my code:

The purpose of the code is to invalidate the session of the user. First, the client should send an ajax call to the logout endpoint providing the user's token and then if the server responds successfully, we call the invalidate() method to clear the user's data from the client side.

import Ember from 'ember';

export default Ember.Controller.extend({
    session: Ember.inject.service('session'),

    actions: { 
       invalidateSession() {
        const url = "http://namespace/logout/";
        let logoutRequest = new Ember.RSVP.Promise(function(r,e){
            r(this.ajax(url, "PUT", {auth_token});)
        },
        if (logoutRequest) {
            this.get('session').invalidate();
        }
      }
    }
});

I Know that my code doesn't working but I can't put it all together...

Using ember-ajax this should work:

ajax: Ember.inject.service(),
....
actions: {
 invalidateSession(){
   return this.get('ajax').request('url_goes_here', {
      method: 'PUT',
      data: {
        some: "additional data"
       },
     }).then(function(success) {
        // inform about successful logout, redirect...
     }).catch(function(error) {
        // handle or throw error 
     });
    }
}

Update : If you want to wrap it around Promises, try this: ...

As @locks mentioned, it is recommended to use the ember-ajax library instead of using raw Ember.$.ajax() . Since this.get('ajax').request() returns a promise, there is no need to wrap it around promises anymore.

However, if all you want to do is logout, I encourage you to take a look at the ember-simple-auth library (addon) which has already solved many features you may need in future (login, logout, invalidation, redirection to login route...).

You can't use this.ajax from a callback like that. But it's unnecessary anyway, as you don't need a new Promise when ajax(…) already returns one. So do just

invalidateSession() {
    const url = "http://namespace/logout/";
    let logoutRequestPromise = this.ajax(url, "PUT", {auth_token});
    return logoutRequestPromise.then((logoutRequestResult) => {
        if (…) {
            this.get('session').invalidate();
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM