我正在使用ng-tags-input将标记添加到Angular + Firebase应用程序中。
我在尝试利用自动完成功能从 firebaseArray 自动填充标签时遇到以下错误,该数组提取存储在我的 firebase 中的现有标签的值/tags
错误
TypeError: Cannot read property 'data' of undefined
这是我的代码...
.HTML
<div class="form-group">
<label for="inputTags" class="col-lg-2 control-label">Tags</label>
<div class="col-lg-3">
<tags-input ng-model="post.tags" >
<auto-complete source="loadTags()"
min-length="1"
load-on-focus="true"
load-on-empty="true"
max-results-to-show="32"></auto-complete>
</tags-input>
</div>
</div>
JAVASCRIPT
$scope.loadTags = function() {
var tagsArray = ['test']; //simply a test value
var tagsRef = new Firebase(FIREBASE_URL + 'tags');
tagsRef.once('value').then(function(snapshot) {
// The Promise was "fulfilled" (it succeeded).
console.log('Promise was fulfilled');
// handle data
angular.forEach (snapshot.val(), function(tag) {
tagsArray.push(tag.name);
});
console.log(tagsArray);
return tagsArray
}, function(error) {
// The Promise was rejected.
console.log('Promise was rejected');
console.error(error);
});
//return tagsArray; <-- This Works, but doesn't include firebaseArray values
};
如您所见,我使用的是最新的Firebase版本(2.4.0),并在Firebase查询中使用了Promises...如果您查看控制台输出,您将看到触发错误后承诺在哪里实现......
TypeError: Cannot read property 'data' of undefined
at ng-tags-input.js:590
at processQueue (angular.js:14792)
at angular.js:14808
at Scope.$eval (angular.js:16052)
at Scope.$digest (angular.js:15870)
at Scope.$apply (angular.js:16160)
at angular.js:17927
at completeOutstandingRequest (angular.js:5552)
at angular.js:5829(anonymous function) @ angular.js:12520(anonymous function) @ angular.js:9292processQueue @ angular.js:14800(anonymous function) @ angular.js:14808Scope.$eval @ angular.js:16052Scope.$digest @ angular.js:15870Scope.$apply @ angular.js:16160(anonymous function) @ angular.js:17927completeOutstandingRequest @ angular.js:5552(anonymous function) @ angular.js:5829
posts.controller.js:15 Promise was fulfilled
posts.controller.js:22 ["test", "firebase", "javascript", "node.js", "angular.js", "bower.js", "npm", "angular.js", "bootstrap"]
问题?
有没有办法将ng-tags-input配置为异步运行,并且仅在实现承诺后加载值?
我将不胜感激任何帮助或建议。
干杯!@FellowHobbyist
ngTagsInput可以很好地处理承诺。您需要做的就是从loadTags
函数返回一个承诺:
$scope.loadTags = function() {
var tagsRef = new Firebase(FIREBASE_URL + 'tags');
return tagsRef.once('value').then(function(snapshot) {
console.log('Promise was fulfilled');
var tagsArray = ['test'];
angular.forEach (snapshot.val(), function(tag) {
tagsArray.push(tag.name);
});
console.log(tagsArray);
return tagsArray;
}, function(error) {
console.log('Promise was rejected');
console.error(error);
return $q.reject(); // <== This is important!
});
};
另请注意我包含在您的代码中的$q.reject()
。当您提供错误回调时,您必须返回被拒绝的承诺,否则整个承诺将被视为已实现。