0

I'm using Vue resource, and trying to make an AJAX call based on the (supposedly-bound) data that came from a previous AJAX call.

I'm trying to bind the data from a call to /me to the userDetails prop (seems to work OK), and pass the userDetails.id into the next function (this.fetchMyProjects()) to get that user's projects. (not working).

WHen I hard-code an ID into this.fetchMyProjects() it binds fine, the trouble is the reference to the this.userDetails object - it's undefined in this context.

I'm failing to understand why I can't access a property that I believe to be bound. Can anyone offer some guidance as to what I'm doing wrong?

Code:

new Vue({
    el : 'body',
    data : {
        projects: [],
        userDetails: {},
    },
    created : function(){

        this.fetchMyUserDetails();
        this.fetchMyProjects();

    },

    methods : {

        fetchMyUserDetails : function(){

            this.$http.get('/me', function(resp){
                this.userDetails = resp.data;
            }).bind(this);

        },

        fetchMyProjects: function(){

            this.$http.get('/projects/user/' + this.userDetails.id, function(projects){
                this.projects = projects.data;
            }).bind(this);

        },


    }

});
  • it might be a problem of times. `vue-resource` calls are asynchronous, so If your `fetchMyProjects` depends on the result of your `fetchMyUserDetails` function, I would call it in the callback of the first function to ensure that your user data is set – Yerko Palma Mar 22 '16 at 12:29
  • Thanks! Chaining the `fetchMyProjects` function call into there worked. – Paul Grimes Mar 22 '16 at 21:20

2 Answers2

0

You've got a misplaced ). .bind() needs to be called on the function directly, in this case on the }:

this.$http.get('/me', function(resp){
    this.userDetails = resp.data;
}.bind(this));
Jeff
  • 24,623
  • 4
  • 69
  • 78
0

This worked:

new Vue({
el : 'body',
data : {
    projects: [],
    userDetails: {},
},
created : function(){

    this.fetchMyUserDetails();
    // this.fetchMyProjects(); // Needed to chain it into fetchMyUserDetails()

},

methods : {

    fetchMyUserDetails : function(){

        this.$http.get('/me', function(resp){
            this.userDetails = resp.data;

            this.fetchMyProjects(); // Works!

        }).bind(this);

    },

    fetchMyProjects: function(){

        this.$http.get('/projects/user/' + this.userDetails.id, function(projects){
            this.projects = projects.data;
        }).bind(this);

    },


}

});