4

我正在尝试在呈现页面之前解析客户列表。使用angularjs组件的解决方案

这里是状态提供程序的参考,我有解决方法。

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 

我可以看到,它的运行决心功能,使作品,但它不会注入方法!有任何想法吗?

回答

5

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

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

这是一个类似于我上个月问 - [如何等待承诺从UI路由器解决角1.5组件](http://stackoverflow.com/questions/38079407/how-to-wait-for-promise-from-ui-router-resolve-in-angular-1-5-component) – Win

+0

所以我试过*完全*像你提供的例子,没有运气:/我不断收到错误:“Uncaught TypeError:无法读取未定义的属性'测试'。你能解释绑定正在做什么,特别是用“<”符号吗? –

+0

上面的代码,我忘了*** $解决。***。你可以再试一次吗?你可以阅读更多在[组件作为路由模板](https://docs.angularjs.org/guide/component#components-as-route-templates) – 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); 
    } 
    ....