1

I am trying to read json file and get data before controller call .But I am not able to display the output why ?

I make one factory like this

.factory('abc',function($http){

  return{
    loadData:function(successCallback,errorCallbak){
      return $http.get('data.json').success(successCallback).error(errorCallbak)
    }

  }


})

I used resolve function like that

resolve: {
        user: function (abc) {
         return abc.loadData

        }
      }

But it not displaying the output in HTML why ?

template: '<b>Welcome {{home.user.name}}!</b>',

Expected output is Welcome Naveen

6
  • while calling abc.loadData i don't see you are passing successCallback & errorCallback there and additionally resolve function returns promise object. but here you have used callback, that might be another reason behind it.. Commented Nov 29, 2015 at 10:57
  • ok i will try and update you Commented Nov 29, 2015 at 10:58
  • Not getting could you please update my plunker Commented Nov 29, 2015 at 11:00
  • I don't see plunkr link here Commented Nov 29, 2015 at 11:03
  • plnkr.co/edit/Whr3a1543uy2Ji8kqJU3?p=preview Commented Nov 29, 2015 at 11:08

2 Answers 2

1

Resolve function should always return a promise, as I said in my comments. So instead of using callbacks you should return promiseobjectfrom theabcserviceloadData` function.

So for converting your service loadData function to promise you need to change .success & .error function to .then function, which returns a promise object ($http.get method returns promise)like .then(successCallback, errorCallbak).

Factory

.factory('abc', function($http) {
  return {
    loadData: function(successCallback, errorCallbak) {
      //returned promise object using `.then` as $http.get function return promise
      return $http.get('data.json').then(successCallback, errorCallbak)
    }
  }
})

Resolve

resolve: {
    user: function(abc) {
      return abc.loadData(success, error);

      function success(res) {
        console.log(res)
        return res.data;
      }

      function error(res) {
        return []; // or whatever default data, maybe {}
      }

    }
}

Demo Plunkr

Sign up to request clarification or add additional context in comments.

Comments

0

You have to provide success and failure callbacks

http://plnkr.co/edit/HBDMMb7CWAN9BXTDz6fb?p=preview

resolve: {
    user: function (abc) {
     return abc.loadData(success, error);
     function success (res) {
       return res.data;
     } 
     function error (res) {
       return []; // or whatever default data, maybe {}
     } 

    }
  }

1 Comment

in your plunkr, you missed the data property, so instead of returning res.data, you just returned res

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.