2014-03-31 28 views
0

試圖建立角工廠/服務消費API數據,這樣我就可以建立默認的索引和顯示的網頁。角HTTP工廠不加載數據查看

我的問題是數據未從工廠返回控制器和視圖。

我的第二個問題是,當我點擊客戶應該再次查詢API,並返回客戶的關注。但是我通過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 
]) 

混了關於如何通過customerID在下面的示例中,我通過靜態JSON文件,但沒有運氣更換URL無論是。 這裏是相應的Plunker http://plnkr.co/edit/G6eFwR7uCNu32cLa1MvV?p=preview

+0

你可以在這裏看看我的回答:http://stackoverflow.com/questions/16930473/angularjs-factory-http-get-json-file/16931623#16931623 –

回答

0

我不是coffeescript專家,但它看起來像你的getCustomers函數返回一個承諾。所以,你需要調用它像這樣:

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

您使用的是GetCustomers的(成功處理)如無物,使用它的返回值是不是真的做任何事情。

如果你想阻止加載控制器,直至HTTP請求返回後,則需要將其設置使用resolve路由。

0

正確的方法是使用.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可以讓你回到你的承諾,並與它的工作!