加载控制器时出错-将AngularJS1迁移到Angular6

时间:2019-10-14 03:29:53

标签: angularjs angular ng-upgrade angular-upgrade

我正在尝试将用AngularJS1编写的组件升级到Angular6。在我的示例中,我通过扩展放置在文件夹“ directive-wrappers ”下的“ UpgradeComponent ”来为所有现有的AngularJS1组件提供包装。当我尝试添加一些没有任何指令的控制器时,出现错误消息

Error: [$injector:unpr] Unknown provider: testDirective2DirectiveProvider <- testDirective2Directive
https://errors.angularjs.org/1.7.8/$injector/unpr?p0=testDirective2DirectiveProvider%20%3C-%20testDirective2Directive
    at eval (angular.js:138)
    at eval (angular.js:4924)
    at Object.getService [as get] (angular.js:5084)
    at eval (angular.js:4929)
    at Object.getService [as get] (angular.js:5084)
    at Function.UpgradeHelper.getDirective (upgrade_helper.ts:56)
    at new UpgradeHelper (upgrade_helper.ts:52)
    at TestDirective2Wrapper.UpgradeComponent (upgrade_component.ts:106)
    at new TestDirective2Wrapper (TestDirective2Wrapper.ts:27)
    at createClass (provider.ts:265) "<app-root _nghost-c69="">"

我尝试添加studentController和homePageController,但无法加载它。有什么想法为什么我要面对这个问题吗? https://stackblitz.com/edit/ng6hybrid-c8h6uv

1 个答案:

答案 0 :(得分:0)

有两个问题需要解决。首先,在studentController.js文件中,您正在使用var mainApp = angular.module("testApp", []);语法来重置AngularJS模块,然后删除之前实例化的所有内容。

要回答有关控制器的问题,不能使用UpgradeComponent(请参阅https://angular.io/guide/upgrade#using-angularjs-component-directives-from-angular-code)直接升级AngularJS控制器,因为它们不是具有模板的组件/指令。这就是为什么您得到的错误(在解决第一个问题之后)是Unknown provider: studentControllerDirectiveProvider <- studentControllerDirective。它找不到用于参考方studentController的指令,因此它添加了Directive来查看该指令是否具有任何内容。

要解决此问题,可以将AngularJS中的控制器转换为带有模板的指令,或者将其转换为AngularJS中的服务,然后使用UpgradeModule将其注入Angular。请记住,此控制器的某个地方需要一个模板,以便可以将其升级到Angular。请在下面的stackblitz中查看此示例。

https://stackblitz.com/edit/ng6hybrid-zs6waw?file=app%2Fdirective-wrappers%2FstudentControllerWrapper.ts