【问题标题】:issue with reciving data from WebApi in AngularJs Service在 AngularJs 服务中从 Web Api 接收数据的问题
【发布时间】:2018-08-04 05:04:13
【问题描述】:

我将在我的应用程序中使用 AngularJS 服务并让一切变得干净整洁。我为此目的关注了一些文章。但它似乎没有完成。对吗??
我没有看到任何错误或其他东西,但是当我设置 Alert(data);我会得到未定义的错误。我在这里错过的工作是什么?

我的 App.js

var app = angular.module('starter', ['ionic'])

我的服务.js

var serverPath = 'http://url/api/locations';

app.service('testService', function($http) {
  this.getLocations = function() {
    $http.get(serverPath).success(function(data) {
      return data;
    });
  };
});

我的控制器.js

app.controller('LocationsController', function ($scope, testService) {
  $scope.locations = testService.getLocations();
});

和我的用户界面

<div ng-controller="LocationsController">
  <ul>
    <li ng-repeat="location in locations">
      {{ location.locationName }}
    </li>
  </ul>
</div>

【问题讨论】:

  • 你在哪里跑Alert(data)
  • @gtlambert 在我的 LocationsController 中。我删除了这一行

标签: javascript angularjs asp.net-web-api angularjs-service angular-promise


【解决方案1】:

一旦您请求数据,您就无法直接从异步调用中获取数据。您应该遵循 Promise 模式来处理异步数据。

我想指出你犯的几个错误。

  1. 您应该从服务方法getLocations 中返回$http.get 承诺,以便您可以将.then 函数放在该方法之上。
  2. 然后在控制器内部从控制器调用服务方法getLocations并放置.then函数,其中第一个将在ajax成功时调用,第二个将在ajax错误时调用。 .then的功能

    this.getLocations = function () {
        return $http.get(serverPath); //return promise object
    };
    

控制器

testService.getLocations().then(function(response){ //success function
     $scope.locations = response.data;
}, function(error){ //error function
     console.log("Some error occurred", error)
});

【讨论】:

  • @MortezaAghili 很高兴听到这个消息。谢谢 :)
  • 我可以将这个方法用于 post 或 put 方法吗?
  • @MortezaAghili this 是什么意思?
  • 让我检查一下,如果是错误,我会为您解释。再次感谢
【解决方案2】:

这是我的做法,因为 $http 里面有承诺

我喜欢在页面中添加一个初始化步骤。

内部服务:

$http.get(serverPath)
  .success(function(data) {
    return data;
  })
  .error(function(err) {
    console.log("some error occured");
    return err;
  });

控制器:

app.controller('LocationsController', function($scope, testService) {
  $scope.init = function() {
    testService.getLocations()
      .success(function(res) {
        $scope.locations = res;
      })
      .error(function(err) {
        console.log("LocationsController, getLocations error:", err);
        // alert(err);
      });
  };
});

标记:

<div ng-controller="LocationsController" ng-init="init()">
  <ul>
    <li ng-repeat="location in locations">
      {{ location.locationName }}
    </li>
  </ul>
</div>

如果您的 http 调用需要一些时间,您也可以添加 ng-hide。

【讨论】:

  • 这只有在服务实际返回承诺时才有效,而它目前没有这样做。
  • 否,.success() 和 .error() 都返回原始承诺以进行附加链接。 (你不应该再使用它们了——它们已被弃用。)
  • @Dave 我想你在说,我在 ^ 上面的回答中做了什么:p
  • 我明白了。 $http.get('/someUrl', config).then(successCallback, errorCallback); 我就把它留在那里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-06
  • 2013-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多