Resolve angularjs from a controller


#1

Hello,

I’m not sure if it is the right place to ask about Angularjs, but i was just wondering if anyone has ever implemented resolve with http request that is in the controller?


#2

You could send http-requests in controllers, services, … but is is recommended to use services/factories to handle such things… to produce reusable code-parts.


#3

thank you I want to implement resolve though but my http request is in the controller.


#4

ah now i got it… ^^ (i think so)

you want to use ui-router resolves? that your requests will be done, before state change and will be injected to your controller?

resolve: {
  propertyData: function($stateParams) {
    return $http.get('xxxxx');
  }
}

In your controller to your state:

myapp.controller('controllerName', function($scope, propertyData) {
  ....
});

#5

thank you, so you put the http request in your app.js file not in the controller. Could you possibly paste your whole code? thank you


#7

Yeah but you have to say us, what does not work… What happens and what should happen.
Is your request working - your url correctly (also mentioned the CORS problem - same origin policy).

What is the response of your request (take a look in chrome web developer tools or firefox firebug under Network)

Is your function called correctly? …


#8

Hello, so I have implemented resolve like this, but Im not sure if this is the correct way, it doesn’t show any errors, but didn’t change the flow much either.
app.js

.state('app.category-info', {
          url: "/category-info/:categoryID/:categoryCount/:categoryName",
          views: {
              'menuContent' :{
                  templateUrl: "templates/category-info.html",
                  controller: "CategoryInfoController",
                  resolve: {
                      myRes: function (dealsFactory) {
                          return dealsFactory.getCategory().then(function (response) {
                              return response.data;
                          });
                      }
                  }
              }
          }
      })

controllers.js

.controller("CategoryInfoController", [ '$scope', 'dealsFactory', '$http', '$stateParams',
             '$location', 'myRes', function($scope, dealsFactory, $http, $stateParams,
                                                   $location, myRes){

        $scope.categoryDeals = [];
        $scope.categoryName = $stateParams.categoryName;


        $scope.navigate = function(url){
            $location.path(url);
        };


                 dealsFactory.getCategory().success(function(data){
                     $scope.categoryDeals = data;

                 });

             }])

services.js

.factory('dealsFactory', ['$http', '$stateParams', function($http, $stateParams) {
        return{
            getCategory : function() {
                return $http({
                    url: 'http://dev.somecompany.net/bigcapi/some/info/moreinfo',
                    method: 'GET',
                    params: {cat_id: $stateParams.categoryID, count: $stateParams.categoryCount, mobileready : 1}
                  })
              }
          }
      }])

#9

Your request is async -> to get the results in your controller you have to return a promise.


#10

ok, thank you, so i should implement promise in my app.js ?


#11

so Ive changed app.js:

.state('app.redemption-instructions', {
          url: "/redemption-instructions/:dealID",
          views: {
              'menuContent': {
                  templateUrl: "templates/redemption-instructions.html",
                  controller: "RedemptionInstructionsController",
                  resolve: {
                      fixBug: function(redeemFactory) {
                          return redeemFactory.getRedemption()
                      }

and services.js

.factory('redeemFactory', ['$http', 'Storage', '$stateParams', function($http, Storage, $stateParams) {
        var token = Storage.get('token');
        return{
            getRedemption : function() {
                 $http({
                    url: 'http://dev.somecompany.net/bigcapi/info/moreinfo/info',
                    method: 'POST',
                    params: {token: token, deal_id: $stateParams.dealID}
                })
            }
        }
    }])

and controller:

$scope.redemptionInstructions = "";


            var token = Storage.get('token');
            $ionicLoading.show({
                content: 'A Minute While We Process Your Order..'
            });
            redeemFactory.getRedemption()
                .success(function (data) {
                    if(data.success === true){
                        $scope.redemptionInstructions = $sce.trustAsHtml(data.mobile_redemption_instructions);
                        $ionicLoading.hide();

However, i get a TypeError: Cannot read property ‘success’ of undefined


#12

if you are using resolves. you do not need to call the getRedemption function again.

If you are changing the state, the resolve waits until your getRedemption call of your state gets resolved and passes the results to your controller.

Controller:

controller('myController', function (resolvedRedemption) {
      // resolve passed resolved redemption to controller as last function argument ;)
});