简体   繁体   中英

How to inject dependency using explicit annotation in angular js

I recently enforcing ng-strict-di in an old code base and now getting warnings and error on running the app. For instance, in the below code

export default angular
    .module("profile", ["ui-router"])
    .controller("profileCtrl", profileCtrl)
    .config(($translateProvider) => {
---
});

I want to understand how I could explicitly define $inject for config as I am getting below error:

function($translateProvider) is not using explicit annotation and cannot be invoked in strict mode

it wants something similar to this:

export default angular
    .module("profile", ["ui-router"])
    .controller("profileCtrl", profileCtrl)
    .config(["$translationProvider", ($translateProvider) => {---}]);

per the documtention on this page: https://docs.angularjs.org/error/ $injector/strictdi "This error occurs when attempting to invoke a function or provider which has not been explicitly annotated, while the application is running with strict-di mode enabled"

and here is a little more explanation: http://frontendcollisionblog.com/javascript/angularjs/2015/03/31/something-no-one-tells-you-about-minifying-angularjs-controllers-until-its-too-late.html

The explicit notation is designed for the code functionality to be maintained through the code minification process. When the javascript is minified the dependencies being injected will be substituted with single characters.Therefore losing there reference. Angular won't have any idea what values the parameters are actually supposed to be and will throw an error.

To rectify this problem, Angular allows explicit dependency annotations. Using an array of strings (ie ["$translationProvider", function($translateProvider)] to associate representations of dependencies. This works because strings don't get minified.

A second method is to use the $inject property which would look like this:

export default angular
    .module("profile", ["ui-router"])
    .controller("profileCtrl", profileCtrl)
    .config(($translateProvider) => {---});
    profileCtrl.$inject = ["$translationProvider"];

The purpose remains the same. For the dependency injections to survive the minification process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM