控制器未从工厂返回数据

Controller not returning data from factory

本文关键字:返回 数据 工厂 控制器      更新时间:2023-09-26

>想象一个监狱,囚犯被关在单独的牢房里,我希望能够通过调用API"/getparameters"来访问特定的牢房,该 API 将返回牢房编号,然后将该变量作为我工厂的 id 传入。这就是我想出的。不返回任何错误,但也不返回任何数据。我哪里出错了?

var app = angular.module('myApp', ['ngResource']);
//app.factory('Params', function)
app.factory ('CellID', function($resource){
    return $resource('/my/api/cell/:id');
});
app.controller('CellCtrl', function($scope, $http, CellID){
    //use $http to getparameters, specifically, the cell number
    $http.get('/getparameters')
    .success(
        function(data) {
            var cellnumber = data.cellnum; 
            CellID.get({id:cellnumber}), function(data){
                $scope.info = data;
            }
        }
    ) 
});

你的括号放在了错误的地方:

CellID.get({id:cellnumber}), function(data){
    $scope.info = data;
}

这是对单元格编号进行get,对结果不执行任何操作,然后只是将函数放入以太中。

我想你的意思是这样做:

CellID.get({id:cellnumber}/* <-- no parenthesis here */, function(data){
    $scope.info = data;
}); // <-- parenthesis here (and a semicolon)

您还应该能够这样做:

$scope.info = CellID.get({id:cellnumber});