1
var newservices = angular.module('newservices', []);
newservices.service('newservice', function ($http) {
return{
newdata: function(parameter){
            return $http.get('/devicedetails/'+parameter).success(function(data)        {
                console.log(data)
                return data

            });

},
}
});

The above service is included in one of my controllers

data=newService.newdata($scope.dummy)
console.log(data)

while trying to print data what i get is $http function object as shown below

Object {then: function, catch: function, finally: function, success: function, error: function} 

why is this so??

3 Answers 3

5

What you see is not an error. It's a Promise. You did an $http GET request, which is asynchronous. $http.getreturns a promise that will be resolved when the remote request is completed. In that moment, you'll get the final value.

See this example, where getShops would be your method newData

 this.getShop = function (id, lang) {
    var promise = $http.get(appRoot + 'model/shops_' + lang + '.json');
    return promise;
 };

In a controller you can use it like this:

   Shops.getShop($routeParams.id).then(function (response) {
       console.log("data is", response.data);
       $scope.shop = response.data[$routeParams.id];
   });

When the data is ready, assign it to a scope.

In your case:

var data;
newService.newdata($scope.dummy).then(function (response) {
   data = response.data;
});
Sign up to request clarification or add additional context in comments.

Comments

2

Your service is returnig a promise

You should use some what like this, not tested though it should work.

data = newService.newdata($scope.dummy).then(function (response) {
                    return response.data;
                },       
                function (error) {
                        return error;
                 });

1 Comment

This is the correct answer. It is the best practice to use promise under all circumstances even if the operation is not asynchronous.
0

You are using it wrong.

This work in promises. so in you controller you need to consume the promisses.

newService.newData($scope.dummy)
  .then(function (data){
    $scope.data = data;
    console.log(data);
  });

Try this.

1 Comment

Ya this ofcourse works.I am trying to directly access data from the service.My method in question works when used along with a resolve function.

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.