angularjsresolveangularjs-componentsangularjs-provider

Use resolve with angularjs component


I am trying to resolve a list of customers prior to rendering a page.

Here is the state provider reference, where I have the resolve methods.

angular.module('app')
  .config(($stateProvider) => {
    $stateProvider
      .state('customers', {
        url: '/customers',
        template: '<customers></customers>',
        resolve: {
          test: function () {
            return 'nihao';
          },
        },
      });
  });

Followed by the component, which should have called the #test from resolve. All it should do, is print the word 'nihao' to the console.

(function myCustomersConfig() {
  class MyCustomersComponent {
    constructor(test) {
      this.test = test;
      console.log(this.test);
    }

  angular.module('app').component('myCustomers', {
    templateUrl: 'app/customers/customers.html',
    controller: MyCustomersComponent,
  });
}());

However, I keep getting this error:

angular.js:13708 Error: [$injector:unpr] Unknown provider: testProvider <- test
http://errors.angularjs.org/1.5.7/$injector/unpr?p0=testProvider%20%3C-%20test
    at angular.js:68
    at angular.js:4502
    at Object.getService [as get] (angular.js:4655)
    at angular.js:4507
    at getService (angular.js:4655)
    at injectionArgs (angular.js:4679)
    at Object.invoke (angular.js:4701)
    at $controllerInit (angular.js:10234)
    at nodeLinkFn (angular.js:9147)
    at angular.js:9553

I can see that it's running the resolve functions, so that works, but it won't inject the methods! Any ideas?


Solution

  • Your code is missing attribute and binding in order for resolve to work.

    angular.module('app')
         ...
           template: '<customers test="$resolve.test"></customers>',           
           resolve: { test: function () { return {value: 'nihao'}; } },
         ...   
      });
    
    (function myCustomersConfig() {
    
       function MyCustomersComponent {
          // You can use test right away, and also view as $ctrl.test
          console.log(this.test);
       }
    
      angular.module('app')
        .component('myCustomers', {
           templateUrl: 'app/customers/customers.html',
           controller: MyCustomersComponent,
           bindings: {
              test: "<",
           }       
      });
    }());