无法在离子模板中显示成功的 angularjs $http从本地服务器获得响应

Cannot display successful angularjs $http get response from local server in ionic template

本文关键字:http 服务器 响应 angularjs 成功 显示      更新时间:2023-09-26

我一生都无法获得此 json 响应以在我的 Ionic 应用程序的制表符视图中呈现。来自本地服务器的响应记录为 200,但我无法将 json 呈现到视图中!我按照本教程来构建工厂和控制器 http://www.benlesh.com/2013/02/angularjs-creating-service-with-http.html,并参考了围绕该主题的堆栈溢出问题:

  1. 无法在 Angularjs 应用程序中的控制器中显示来自工厂的 HTTP 获取响应

  2. 使用 Angular 将 JSON 数据从本地 Web 服务器输出到 Ionic 应用程序

  3. Angularjs $http.get 不起作用

  4. Angularjs $http.get not work

我已经包括了我的控制器.js、负责执行 api 调用的工厂和模板代码。提前感谢您提供的任何帮助,我很感激!

控制器.js

(function(){
    angular.module('athenaApp.controllers', [])
        .controller('DashCtrl', function($scope, athenaApiService, $timeout) {
            athenaApiService.getArticles().then(function(data){
                $scope.news = data;
           })
      })
}());

服务.js

.factory('athenaApiService', function($http){
    return{
        getArticles: function(){
            return $http.get('http://localhost:8000/athenaAPI/articles').then(function(result){
                return result.data;
            });
        }
    }
}); 

制表符破折号.html

 <ion-view view-title="News">
  <ion-content>
      <ion-refresher on-refresh="doRefresh()">
      </ion-refresher>
      {{news}}
      <ion-list ng-repeat='article in news'>
        <a class="item item-thumbnail-left" href="#/tab/news/{{article.id}}"> <!-- "#/tab/news/{{article.id}}" -->
          <img src='../img/ionic.png'>
          <div class='item item-text-wrap'>
              <h3>{{article.headline}}</h3>
              <p>{{article.byline}}</p>
          </div>
        </a>
      </ion-list>
  </ion-content>
</ion-view>

服务器输出

Listening on port: 8000
Articles Requested...
[ { id: 0,
    headline: 'Headline 0',
    byline: 'Author 0',
    datePublished: '3/4/5',
    content: { para0: 'This is a sentence', para1: 'And another sentence.' },
    originalUrl: '' },
  { id: 1,
    headline: 'Headline 1',
    byline: 'Author 0',
    datePublished: '3/5/5',
    content: { para0: 'This is a sentence', para1: 'And another sentence.' },
    originalUrl: '' },
  { id: 2,
    headline: 'Headline 2',
    byline: 'Author 0',
    datePublished: '3/6/5',
    content: { para0: 'This is a sentence', para1: 'And another sentence.' },
    originalUrl: '' },
  { id: 3,
    headline: 'Headline 3',
    byline: 'Author 0',
    datePublished: '3/7/5',
    content: { para0: 'This is a sentence', para1: 'And another sentence.' },
    originalUrl: '' } ]
GET /athenaAPI/articles 200 39.072 ms - 669
结果

是一个数组,这就是为什么result.data是未定义的。直接回报承诺即可。

getArticles: function(){
        return   $http.get('http://localhost:8000/athenaAPI/articles');
}

对不起,vbordo,我正忙着为你制作一个CodePen,但我找到了一些方法来改进你想要做的事情。 <ion-list>建议通过ion-item重复的最佳实践,我也建议使用angular.forEach来构建$scope.news数组,这样您就不会消除角度数组绑定。

请参阅我的工作代码示例,其中包含使用您的 athena 数据服务的示例 JSON 数据集。

http://codepen.io/goneale/pen/ONbRrr?editors=1011