I am trying to wrap the getstream API in an angular service (factory)
Here is my code:
.factory('FeedStream', function($http, $q) {
var client = stream.connect('xxxxxxxxxxx');
return {
feed : function() {
$http.get('/api/feed/auth/')
.success(function(auth) {
var user_feed = client.feed('user', auth.user, auth.token);
console.log(user_feed.get());
user_feed.get().then(function(data) {
console.log(data);
return data;
})
})
},
}
First I get the user_id and auth token from my server using the endpoint /api/feed/auth/. This data is returned in an angular promise.
Next, I use this data to call the getstream api to get the user_feed
object. If I return this object (user_feed
) it is undefined in the controller. If I print it to the console here in the service, it has the correct value. I've noticed that the print happens half a second or so after the return. Why is the assignment of this variable happening asynchronously?
Now if I call the get
method on this user_feed
object inside a console.log statement, a Javascript promise object is printed out. If I return user_feed.get()
it returns undefined
to the controller. If I call it here in the service like in my code above, and return the data object in the promise then statement, it returns undefined
to the controller. However if I print the data
object, it has the correct value.
Why can't I return any objects from this service? Am I missing some fundamental aspect of using promises?
You haven't returned feed promise object
as well as data
haven't been returned from feed
method correctly. So for achieving the same thing do use .then over $http to maintain promise chaining
Code
return {
feed : function() {
//return `$http.get` promise
return $http.get('/api/feed/auth/')
.then(function(response) {
var auth = response.data;
var user_feed = client.feed('user', auth.user, auth.token);
console.log(user_feed.get());
//return `$http.get` to return internal promise
return user_feed.get().then(function(data) {
console.log(data);
return data;
})
})
},
}
Controller
FeedStream.feed().then(function(data){
console.log("data returned by user feed", data)
})