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); 
    } 
    ....