0

I am new to AngularJS trying to create my own Custom Service. I am using $http method. Here is my code

HTML:

<div ng-app="dummyApp">
<div ng-controller="myserctrl">
    <label>My label</label>
    {{resData}}
</div>

Ctrl:

var myreq = angular.module("dummyApp", []);
myreq.controller('myserctrl', function($scope, myService, $rootScope) {
    $scope.resData = result.data.content;
});

Service:

myreq.service("myService", function($rootScope, $http){
$rootScope.result = {};
$http.get('https://api.myjson.com/bins/dtm5r')
.then(function (data) {
    result = data;
    console.log($rootScope.result);
})
.then(function (data){
    console.log("the Data is error")
})
});

My call was going and I am getting the successful result but I am missing something in the control, because I am not getting the proper data in the html.

halfer
  • 19,824
  • 17
  • 99
  • 186
Mr.M
  • 1,472
  • 3
  • 29
  • 76
  • use $rootScope.result instead of just "result" wherever you are using it. i.e in service(inside 1st then) as well as in controller. Also your error handling of http will not work. – Abhishek Jha Jul 21 '17 at 05:44
  • Please share the plnkr/jsfiddle of the code simulating issue – Harpreet Jul 21 '17 at 06:15
  • @AbhishekJha Don't use $rootScope for that. – Nikolaj Dam Larsen Jul 21 '17 at 06:44
  • @NikolajDamLarsen that suggestion was to make program syntactically correct as he is new to angular js. Going forward he will learn how and when to use $rootScope. Nevertheless I agree rootScope should not be used for such use case – Abhishek Jha Jul 21 '17 at 08:47
  • @AbhishekJha can you please tell me how use success & error callback – Mr.M Jul 21 '17 at 08:50
  • @AbhishekJha I very rarely use $rootScope for anything. Everything you could think to do with $rootScope, you could do better with the different types of providers. I pretty much only ever use the $rootScope for events. – Nikolaj Dam Larsen Jul 21 '17 at 09:33
  • @Mahadevan the success and error callbacks are deprecated (assuming you mean `.success()` and `.error()`) since they don't return promises and thus doesn't support chaining. You "always" want to use `.then()` with $http. To handle an error using `.then`, you have two options. The then function takes a second callback that'll be called if the http request fails: `.then(function(res){ /* success */ }, function(res){ /* error */ })`. Alternatively, you can use the `.catch([callback])` function. As Vishal said in his answer, you ought to go learn how Promises works. That'll help a lot. – Nikolaj Dam Larsen Jul 21 '17 at 09:38
  • the way @Nikolaj has suggested is how you handle these. you can read more about it here https://docs.angularjs.org/api/ng/service/$http – Abhishek Jha Jul 21 '17 at 09:41

2 Answers2

3
 myreq.service("myService", function($rootScope, $http){
  // $rootScope is persistent but it is not available
  this.getData = function(){
      return $http.get('https://api.myjson.com/bins/dtm5r');
  }
});


    var myreq = angular.module("dummyApp", []);
    myreq.controller('myserctrl', function($scope, myService, $rootScope) {
        myService.getData().then(function (data) {
            $scope.resData = data;
            console.log($rootScope.result);
        });

});

I'd suggest you to go through the asynchronous nature of AJAX and what a Promise is, these should help you understand the behaviour better.

  • Hi I have a query here but how to use success call back and error call back here can you tell me – Mr.M Jul 21 '17 at 06:39
  • Can you please explain me why you have modified my service and control – Mr.M Jul 21 '17 at 06:44
  • 2
    Because $http is asynchronous, so when you call `$scope.resData = result.data.content;` in your controller the `data` property of the result object is undefined. Thus you get an error. Using @Vishal's change, allows your controller to wait for the $http request to finish, before trying to access any data. – Nikolaj Dam Larsen Jul 21 '17 at 06:47
  • With the above code i am getting entire json data but i want only content while i am trying data.content it was not coming {"data":{"id":1,"content":"Hello, World!"},"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"https://api.myjson.com/bins/dtm5r","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"} – Mr.M Jul 21 '17 at 06:52
  • Sorry I got the result thanks for the help – Mr.M Jul 21 '17 at 06:55
  • Yeah, he made a small "mistake" in the controller. The `data` argument ought to be called `response`, since $http resolves to response objects. So you'd change `data` to `response` in the argument, and replace `data` in the assignment to `$scope.resData = response.data.content`. – Nikolaj Dam Larsen Jul 21 '17 at 06:55
  • One small query here how use success and error callback here – Mr.M Jul 21 '17 at 07:01
0

In your controller change

$scope.resData = result.data.content;

to

$scope.resData = $rootScope.result.data.content;

And In your

Service

change result = data; to $rootScope.result = data;

Wasif Khan
  • 956
  • 7
  • 25