javascript - 在 AngularJs 服务中从 Web Api 接收数据时出现问题

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

我将在我的应用程序中使用 AngularJS 服务,并使一切变得干净漂亮。为此我遵循了一些文章。但它似乎还没有完成。对吧??
我没有看到任何错误或其他东西,但是当我设置警报(数据)时;我会收到未定义的错误。我错过了什么工作要做?

我的App.js

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

我的Service.js

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

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

我的controller.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>

最佳答案

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

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

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

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

Controller

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

关于javascript - 在 AngularJs 服务中从 Web Api 接收数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35491009/

相关文章:

javascript或jquery倒计时操作更新mysql表

javascript - 模块模式和 document.ready

javascript - 在 jquery 函数中使用 php 中的 javascript 变量

angularjs - 手动引导 AngularJS,然后获取模块

asp.net-web-api - 如何从远程计算机查看由 VS Code 提供服务的 .net core 2 站点?

mysql - 如何通过 ASP.net API 和 Postman 删除 mysql 中的记录?

javascript - 如何衡量 promise 的执行时间?

javascript - 使用 AngularJs NgResource 从本地主机加载 JSON 文件

javascript - 如何以 Angular 连续顺序运行异步

asp.net-mvc - ASP.NET MVC 4应用程序调用远程WebAPI