【问题标题】:Angular http factory not loading data to viewAngular http工厂未加载数据以查看
【发布时间】:2014-04-01 03:55:27
【问题描述】:

尝试设置 Angular 工厂/服务来使用 API 数据,这样我就可以构建默认索引和显示页面。

我的问题是数据没有从工厂返回到控制器和视图。

我的第二个问题是当我点击客户时,它应该再次查询 API 并返回相关客户。但是我对如何通过customerID 传递routeParams 感到困惑

app.factory('apiFactory', ["$http", "$routeParams", ($http, $routeParams) ->
  factory = {}

  factory.getCustomers = ->
    $http(
      method: "GET"
      url: "/customers.json"
    ).success( (data) ->
      data
    ).error( (status) ->
      console.log "Error"

  factory.getCustomer = (customerId) ->
    customerId = $routeParams.customerID
    customer

  factory
])

app.controller("CustomersController", ["$scope", "apiFactory", ($scope, apiFactory) ->
  $scope.customers = apiFactory.getCustomers()
  console.log $scope.customers

  $scope.customer = apiFactory.getCustomer
  console.log $scope.customer
])

在以下示例中,我将 url 替换为静态 json 文件,但也没有运气。 这里是对应的 Plunker http://plnkr.co/edit/G6eFwR7uCNu32cLa1MvV?p=preview

【问题讨论】:

标签: javascript angularjs http


【解决方案1】:

我不是咖啡脚本专家,但看起来您的 getCustomers 函数正在返回一个承诺。所以你需要这样称呼它:

apiFactory.getCustomers().success( (data) ->
    $scope.customers = data);

您在 getCustomers() 中使用的成功处理程序实际上并没有做任何事情,因为没有使用它的返回值。

如果您想阻止控制器在 http 请求返回之前加载,那么您需要使用 resolve 在路由中进行设置。

【讨论】:

    【解决方案2】:

    正确的方法是使用.then()

    factory.getCustomers = ->
    $http(
      method: "GET"
      url: "/customers.json"
    ).then( (data) ->
      data;
    ).error( (status) ->
      console.log "Error"
    

    在你的控制器中:

    apiFactory.getCustomers().then(function(data) ->
        $scope.customers = data
    );
    

    .then 让您兑现承诺并兑现承诺!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 2015-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 1970-01-01
      相关资源
      最近更新 更多