繁体   English   中英

Angular http工厂未加载数据以查看

[英]Angular http factory not loading data to view

尝试设置Angular工厂/服务以使用API​​数据,因此我可以构建默认索引并显示页面。

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

我的第二个问题是,当我单击客户时,它应该再次查询API并返回相关客户。 但是我对如何通过routeParams传递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
])

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

我不是coffeescript专家,但看来您的getCustomers函数正在返回诺言。 因此,您需要这样称呼它:

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

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

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

正确的方法是使用.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使您能够兑现诺言并与之合作!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM