我已经在我的AngularJS应用程序中使用了Value()模块。 我已经声明并修改了值,但我无法在控制器中检索修改后的值或最新的值。
-
流程如下:
- 第 1 步:使用 .value("键": "值") 初始化值
- 第 2 步:修改 RUN 块中的值。如果我在这个步骤中做 console.log(),我会得到想要的输出。这意味着值正在更新。
- 第 3 步:在控制器中访问该修改值或最新值以进行进一步处理。
我在下面的代码中提到了步骤。
app.module.js
(function () {
"use strict";
angular
.module("app", [
"app.authentication"
])
//STEP 1: Initialize the Value.
.value("errorCollectionObject", {})
.run(getErrorCollection)
function getErrorCollection($rootScope, $location, $http, errorCollectionObject) {
$rootScope.$on('$routeChangeStart', function (event, next, current) {
$http.get("../app/core/error-collection.json")
.then(function (response) {
//STEP 2: Modify/Update the Value.
errorCollectionObject = response.data;
});
});
}
})();
login.controller.js
(function () {
"use strict";
angular
.module("app.authentication")
.controller("LoginController", LoginController)
LoginController.$inject = ["errorCollectionObject"];
function LoginController(errorCollectionObject) {
var vm = this;
//STEP 3: Use the Modified or Latest Value
//But instead of getting the Modified value, I am getting the null Object {} that I initialized in STEP 1.
console.log(errorCollectionObject);
//Output is: {}
}
})();
知道出了什么问题吗?还是我以错误的方式实现了这个概念?任何帮助将不胜感激。
我以错误的方式实现价值模块概念。在我的实现方法中,值不是通过引用传递的。因此,我没有获得修改或更新的值。
为了通过引用传递值并实现上述功能,请按如下方式修改步骤:
第 1 步:
var errObj = {errorCollection: null};
.value("errorCollectionObject", errObj)
第 2 步:
errorCollectionObject.errorCollection = response.data;
第 3 步:
console.log(errorCollectionObject.errorCollection);
您将在步骤 3 中获得修改或更新的值。 希望它对某人有所帮助。:)