我的 Angular 应用程序中的 services.js
中有这段代码:
.factory('Articles', function($http) {
$http.get('https://api.myjson.com/bins/4ici6').then( function(response) {
var articles = response.data.articles;
});
return {
all: function() {
return articles;
},
get: function(articleId) {
for (var i = 0; i < articles.length; i++) {
if (articles[i].id === parseInt(articleId)) {
return articles[i];
}
}
return null;
}
};
})
它不起作用,因为我在控制台中收到此错误:
ReferenceError: articles is not defined
at Object.all (http://localhost:8100/js/services.js:31:14)
at new <anonymous> (http://localhost:8100/js/controllers.js:4:30)
at Object.instantiate (http://localhost:8100/lib/ionic/js/ionic.bundle.js:18015:14)
这里还有引用文章
的controller.js
代码:
.controller('NewsCtrl', function($scope, Articles) {
$scope.articles = Articles.all();
})
.controller('NewsDetailCtrl', function($scope, $stateParams, Articles) {
$scope.article = Articles.get($stateParams.articleId);
$scope.posttofacebook = function (){
window.plugins.socialsharing.shareViaFacebook(null, null, $scope.article.url);
}
$scope.posttotwitter = function (){
window.plugins.socialsharing.shareViaTwitter(null, null, $scope.article.url);
}
})
我在这里做错了什么?
最佳答案
因为 $http.get
是一个异步调用,所以您必须处理它。
仅仅将它放在你的工厂之上并不能始终如一地工作。
试试这个:
.factory('Articles', function($http) {
return {
all: function() {
return $http.get('https://api.myjson.com/bins/4ici6').then(function(response) {
return response.data.articles;
});
},
get: function(articleId) {
//Probably best here to call an API endpoint that will return a single article with the parameter's articleId
//Something along the lines of
//$http.get('https://api.myjson.com/bins/4ic16/' + articleId).then(function(response) { //handle response});
}
};
})
您的 Controller 也应该更改为处理异步函数调用:
.controller('NewsCtrl', function($scope, Articles) {
Articles.all().then(function(articles) { $scope.articles = articles });
})
关于javascript - Angular JS/文章未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40357982/