Angular嵌套服务调用

时间:2014-11-18 12:09:45

标签: angularjs angularjs-scope

此代码:

    Requests.getRequests(user.id).then(function (requests) {
    for (var i = 0; i < requests.length; i++) {
        loadProfileTrips(requests[i]);
        // get Profile information

    }
})

var loadProfileTrips = function (request) {
    Profile.get(request.from).then(function (profile) {
        // get Trip Detail information
        Trips.getTripDetail(request.trip).then(function (trip) {
            console.log(profile[0].username);
            console.log(trip[0].title);
            $scope.requestedProfileTrips.push(profile[0].username, trip[0].title);
        });

    });
}

我需要连续进行3次服务调用。每个服务调用取决于解析之前服务调用的值。现在如何将这些调用链接起来并获得包含所有三个值的$ scope.value呢?

1 个答案:

答案 0 :(得分:2)

i上没有创建调用异步和闭包的代码问题。如果以这种方式重写代码,它应该可以工作:

Requests.getRequests(user.id).then(function (requests) {
    for (var i = 0; i < requests.length; i++) {
        loadProfileTrips(requests[i]);
        // get Profile information

    }
})

var loadProfileTrips = function (request) {
    Profile.get(request.from).then(function (profile) {
        // get Trip Detail information
        Trips.getTripDetail(request.trip).then(function (trip) {
            console.log(profile[0].username);
            console.log(trip[0].title);
        });

    });
}