javascript - Angular JS/文章未定义

标签 javascript angularjs

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

相关文章:

javascript - jQuery gmaps 标记信息窗口不会在启动时显示

javascript - d3 javascript点击函数调用

unit-testing - 具有 SignalR 依赖项的服务单元测试的 Karma 配置

javascript - 什么会导致 setTimeout(callback, 0) 的回调延迟

javascript - 使用 Javascript 克隆();使独立标题跟随页面

javascript - 为什么我的函数在工作和 JavaScript 之间交替

javascript - 如何使用 Javascript 在网络中广播消息?

javascript - 使用 $emit from 指令将事件发送到 Controller

css - 如何在angularjs中将事件类添加到菜单

javascript - 最新的 Google Angular CDN 不工作