[英]Factory not passing $http.get based object array to controller in angular.js
我只是从Angular开始,所以在某个问题上已经停留了一段时间。
我的工厂正在正确创建一个包含对象,RSS提要数据的数组,并将其加载到控制台。 问题是我似乎无法使数组返回到控制器。
任何帮助,将不胜感激。 请原谅草率的代码。
Main.js
function FeedCtrl($scope, GetFeed) {
$scope.itemId = 0;
//$scope.items = [];
console.log('Get episodes in ctrl');
$scope.items = function() {
return GetFeed.getEpisodes();
};
console.log('display items from ctrl');
console.log($scope.items());
$scope.itemId = function(index) {
$scope.itemId = index;
console.log($scope.itemId);
console.log($scope.itemNames[$scope.itemId].title);
};
};
function EpisodeCrtl($scope, GetFeed) {
//getFeed.pullFeed();
};
function GetFeed($http){
var episodeArray = [];
function items(){
console.log('Firing pullFeed');
return $http.get('assets/feed.xml').then(function(response) {
var x2js = new X2JS()
var itemDef = x2js.xml_str2json(response.data);
itemsObj = itemDef.rss.channel.item;
var numOfItems = itemsObj.length;
episodeArray.length = 0;
for (var i = 0; i < numOfItems; i++) {
episodeArray.push({
title: itemsObj[i].title,
link: itemsObj[i].link,
author: itemsObj[i].author,
pubDate: new Date(itemsObj[i].pubDate),
summary: itemsObj[i].summary,
duration: itemsObj[i].duration,
description: itemsObj[i].description
});
}
console.log(episodeArray);
return episodeArray;
})
};
return {
getEpisodes: function(){
console.log(episodeArray);
episodeArray.length = 0;
items();
console.log(episodeArray);
return(episodeArray);
}
}
};
var app = angular.module('ctApp', ['ngMaterial', 'ngAnimate', 'ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'list.html',
controller: 'FeedCtrl'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'EpisodeCrtl'
});
})
.config( [ '$compileProvider', function( $compileProvider ) {
var currentImgSrcSanitizationWhitelist = $compileProvider.imgSrcSanitizationWhitelist();
var newImgSrcSanitizationWhiteList = currentImgSrcSanitizationWhitelist.toString().slice(0,-1)
+ '|chrome-extension:'
+currentImgSrcSanitizationWhitelist.toString().slice(-1);
}
])
.factory('GetFeed', GetFeed)
.controller('FeedCtrl', FeedCtrl)
.controller('EpisodeCrtl', EpisodeCrtl);
您需要了解异步调用和承诺的工作方式。 你似乎是在第一正确的做事情-你正在做的return
上$http.get
通话-这个返回的承诺。 你正在做的return
上episodeArray
的范围内.then
处理程序。 这是对的。
但是,然后在以下函数定义中:
getEpisodes: function(){
console.log(episodeArray);
episodeArray.length = 0;
items(); // this returns immediately and does not yet have the data
console.log(episodeArray);
return(episodeArray);
})
对items
的调用立即返回。 episodeArray
仍然为空。 您返回空数组对象[]
。
因此,您需要return items()
-这将返回$http.get().then()
承诺。
getEpisodes: function(){
return items();
})
然后,您不能只将返回值分配给$scope.items
在当前代码中,它只会分配相同的空数组[]
。 显然,如果兑现了诺言-这不是您所需要的。 相反,您必须先在控制器中添加.then
然后在其中分配值:
GetFeed.getEpisodes().then(function(episodeArray){
$scope.items = episodeArray;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.