[英]Javascript variable becomes undefined when passed as an argument to a function
我有一個帶有服務的角度程序,其中包含當前值的映射(非常類似於上下文)。 在程序的不同位置,我調用該服務以獲取某物的currentValue。 該服務稱為CrsViewContext,方法非常簡單
.service('CrsViewContext', function () {
var currentInstances = {};
this.setCurrent = function (domain, instance) {
currentInstances[domain] = instance;
console.log('ViewContext setCurrent: ' + domain);
console.dir(instance);
};
this.getCurrent = function (domain) {
console.log('ViewContext getCurrent: ' + domain);
console.dir(currentInstances[domain]);
return currentInstances[domain];
};
this.resetCurrent = function (domain) {
console.log('ViewContext resetCurrent: ' + domain);
currentInstances[domain] = null;
};
});
在我的控制器中,我將此CrsViewContext作為參數傳遞,並執行類似的操作
.controller('MyCtrl', function (CrsViewContext) {
var n = CrsViewContext.getCurrent ('RealEstate');
console.log ("get current Real estate");
console.dir (n);
console.log ("current real estate id: "+n.id);
});
但是,即使在我的控制台中,我仍然可以看到先前的語句返回了一個定義id及其值的對象,因此最后一個日志變得不確定
因為我使用Restangular來檢索該對象,所以與Javascript和/或Restangular有關。 另外請注意,如果您從控制台訪問它,則獲取ID毫無問題
n=$('#wrapper').injector().get('CrsViewContext').getCurrent('RealEstate').id;
從控制台返回3
提前致謝
帕斯卡
經過大量的撥弄之后,我刪除了對代碼中前面的變量進行的$ object調用。 Restanglar返回了promise,據我的理解,在promise上調用$ object可以保證返回其值,但不會。 保持這些變量為諾言似乎可行。 真的不明白為什么–
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.