未定义Angular JS/文章

Angular JS / articles is not defined

本文关键字:文章 JS Angular 未定义      更新时间:2023-09-26

我的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)

这里还有指articles:的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('NewsCtrl', function($scope, Articles) {
  Articles.all().then(function(articles) { $scope.articles = articles });
})

您的articles变量在http的回调中声明,因此它在回调之外不可用。将其移到外部:

.factory('Articles', function($http) {
    // declaring it here makes it available in the 'all' function
    var articles = [];
    $http.get('https://api.myjson.com/bins/4ici6').then( function(response) {
        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;
        }
    };
})

但是,由于您是通过http异步获取文章的,因此可能会在获取文章之前执行Articles.all(),从而导致空数组。相反,我会这样做:

.factory('Articles', function($http, $q) {
    // declaring it here makes it available in the 'all' function
    var articles = [];
    var fetched = false;
    var getAll = function() {
        var deferred = $q.defer();
        if (!fetched) {
            $http.get('https://api.myjson.com/bins/4ici6').then( function(response) {
                articles = response.data.articles;
                fetched = true;
                deferred.resolve(articles);
            });
        } else {
            deferred.resolve(articles);
        }
        return deferred.promise;
    }
    return {
        all: getAll,
        get: function(articleId) {
            var deferred = $q.defer();
            getAll().then(function(articles) {
                for (var i = 0; i < articles.length; i++) {
                    if (articles[i].id === parseInt(articleId)) {
                        deferred.resolve(articles[i]);
                        break;
                    }
                } 
                // not found
                return deferred.reject();
            }
            return deferred.promise;
        }
    };
})

并像这样使用:

Articles.all().then(function(articles){
    // now the articles are available
});
Articles.get(id).then(function(article){
    // found   
}, function(){
    // not found
});