从REST调用获取ID,然后在另一个REST调用Angular JS中使用它

时间:2017-06-09 18:02:34

标签: javascript angularjs rest

我试图实现这个目标: 我调用了一个REST api并获取了一个ID,之后我使用该ID调用另一个REST API并从中获取所选ID的数据。我必须使用相同的ID在相同的角度视图上执行更多REST调用。

这是我在控制器中的代码的样子:

.controller("ReservationCtrl", function($scope, $stateParams, Reservations, Clients, Apartments) {
    // Getting ID from  URL & $state
    $scope.currentReservation = Reservations.get({ reservationId: $stateParams.reservationId });

    // I'm trying to get guest data by forwarding an ID from the currentReservation, but I'm getting angular error
    $scope.guest = Clients.get({ clientId: currentReservation.clients_id });

    // The same situation here, but now, as a function which I'm calling from the view I can get the ID, but when I call it from a pressed button, not from ng-init...
    $scope.apartment = function(id){
            return Apartments.get({apartmentId: apartments_id});
    };
});

所以,正如我在代码中写的那样,当我从视图中调用单元函数时,我只能使用一个按钮来获取数据,我必须单击该按钮来加载数据,所以这没有用。

有什么方法可以解决这个问题? 非常感谢。

2 个答案:

答案 0 :(得分:0)

我在@Adrian Smith的回答帮助下解决了这个问题,谢谢@Adrian Smith。我使用Angular的$ promise来运行其他调用。

所以这是适合我的代码:

.controller("ReservationCtrl", function($scope, $stateParams, Reservations, Clients, Apartments) {
Reservations.get({ reservationId: $stateParams.reservationId })
.$promise.then(function(res){
    $scope.guest = Clients.get({ clientId: res.clients_id });
    $scope.apartment = Apartments.get({apartmentId: res.apartments_id});
    // .. and so on for every request which includes an ID from the Reservations REST call.
});

答案 1 :(得分:-1)

我们无法看到您服务的内部,但我猜测这些服务会返回承诺,而不是价值。问题是当Clients.get尝试运行时,没有分配$ scope.currentReservation.client_id。

另外几个变量不在范围之前,但我假设这只是一个错字。

这个修改过的控制器应该解决这两个问题。

.controller("ReservationCtrl", function($scope, $stateParams, Reservations, Clients, Apartments) {
    // Getting ID from  URL & $state
    Reservations.get({ reservationId: $stateParams.reservationId })
    .then(function(res) {
      $scope.currentReservation = res;
    })
    .then(Clients.get({ clientId: $scope.currentReservation.clients_id }))
    .then(function(res) {
      $scope.guest = res;
    })
    .catch(function(err) {
      console.error("Error: ", err);
    })

    // The same situation here, but now, as a function which I'm calling from the view I can get the ID, but when I call it from a pressed button, not from ng-init...
    $scope.apartment = function(id){
            return Apartments.get({apartmentId: $scope.apartments_id});
    };
});