使用resolve与AngularJS组件

11

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

这里是状态提供程序参考,我在其中有解析方法。

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

在组件调用#test时,紧跟着的应该是resolve。它所需要做的就是将单词“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

我可以看到它正在运行解析函数,所以这方面没问题,但它不会注入方法!有任何想法吗?

2个回答

8

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

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 1.5 组件中等待 UI Router Resolve 的 Promise - Win
所以我尝试完全按照你提供的例子,但没成功 :/ 我一直收到错误信息:"Uncaught TypeError: Cannot read property 'test' of undefined"。你能解释一下绑定(bindings)是做什么的,特别是那个"<"符号吗? - Tori Huang
上面的代码,我忘记了 $resolve。你能再试一次吗?你可以在组件作为路由模板中阅读更多信息。 - Win
非常感谢您迄今为止的帮助!因此,如果不注入“test”,我就不会再收到上述错误。但是,我已经匹配了这些更改,包括$resolve,现在console.log(this.test)返回“未定义”。有什么想法吗? - Tori Huang
如果test是一个字符串,则返回“你好”。您想使用bindings: { 'test': '@' },就像Angular文档中所示的那样。 - Win

1
给你的组件添加绑定并将其从控制器函数中移除。
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);
    }
    ....

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接