0

I'm building a MEAN stack app, where I need to return a logged in users email address, in order to pass it into a $http.get statement, as a parameter, in order to return data for display.

I am currently trying to do this in a factory, this is the endpoint I have for returning the current logged in user;

$http.get('/api/users/me') 
          .then(function(result) {
            userId = result.data.email;
          });

This endpoint works, and if I console.log within the function it will return the email of the logged in user, if I console.log outside, then it returns undefined.

I was wondering if it would be possible to either nest, or use .then or .success in order to pass the returned email address from the original $http.get into a second request, which would look something like this;

$http.get('/api/bets', {params: {"created_by": userId}});

Pretty new to Angular, so if you have any suggestions on where to start with a solution, it would be mighty helpful!

2 Answers 2

3

You can return another promise from within the callback, and it will be chained:

$http.get('/api/users/me') 
      .then(function(result) {
        return $http.get('/api/bets', {params: {"created_by": result.data.email}});
      })
      .then(function(result){  
           //result of /api/bets 
      });
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks guys, this is awesome, and now I'm getting the right params passed in; config: Object headers: Object method: "GET" paramSerializer: ngParamSerializer(params) params: Object created_by: "[email protected]" however, it's still returning every object, regardless of the params, any thoughts?
Sounds like that is something on the server side... Assuming you are using WebAPI, it might expect that you send a post instead of a get, or maybe the parameter does not match up with what is expected. Put a breakpoint in the server side handler to see what is there.
2

Just chain the promises by returning another $http.get from within your first handler.

$http.get('/api/users/me') 
          .then(function(result) {
            userId = result.data.email;

            // make the next call
            return $http.get('/api/bets', {params: {"created_by": userId}});
          }).then(function (result) {
            // result of last call available here
          });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.