使用带有 angularjs 组件的 resolve

Use resolve with angularjs component

我正在尝试在呈现页面之前解析客户列表。

这是状态提供者参考,其中有解析方法。

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

后面是组件,它应该从解析中调用#test。它应该做的就是将单词 'nihao' 打印到控制台。

(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,
  });
}());

但是,我不断收到此错误:

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

我可以看到它是 运行 解析函数,所以它可以工作,但它不会注入方法!有什么想法吗?

您的代码缺少属性和绑定以使解析正常工作。

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: "<",
       }       
  });
}());

向您的组件添加绑定并将其从您的控制器函数中移除

angular.module('app').component('myCustomers', {
    templateUrl: 'app/customers/customers.html',
    controller: MyCustomersComponent,
    bindings: {
        'test': '<' // or @ for string
    }
});

class MyCustomersComponent {
    constructor() {
      // this.test should already exist
      console.log(this.test);
    }
    ....