回调不与Angularjs一起使用?

时间:2017-10-26 08:59:56

标签: javascript jquery angularjs getjson asynccallback

我是javascript中的承诺和回调的新手。在我的项目中,我尝试使用getJSON来获取信息并在我的控制器中使用它。以下是我到目前为止的情况:

vm.addStop = function () {
    vm.isBusy = false;
    var result;
    try {
        vm.getCoords(vm.newStop.name, function (result) {
            console.log("Trying to use this callback: ");
            console.log(result);
            // callback worked? continue from here
            var newStop = sqlFactory.addStop(vm.newStop.name, result.lat, result.lng, vm.newStop.stopDate, vm.tripNum);
            vm.stops.push({
                id: parseInt(newStop.id),
                name: String(newStop.name),
                latitude: result.lat,
                longitude: result.lng,
                stopDate: new Date(vm.newStop.stopDate),
                tripNum: parseInt(newStop.tripNum)
            });
        });
    }
    catch (err) {
        vm.isBusy = false;
        vm.errorMessage = "Error saving stop: " + err;
    }
};

vm.getCoords = function (name, callback) {
    var location = name;
    var result = "";
    location = location.replace(" ", "+");
    var url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + location + "&key=key";

    $.getJSON(url)
        .done(function (data) {
            result = {
                lat: data.results[0].geometry.location.lat,
                lng: data.results[0].geometry.location.lng
            };
            callback(result);
        })
        .fail(function (err) {
            result = "error";
        });
};

我的问题是,当我尝试使用回调中的数据并将其推送到vm.stops时,它似乎并没有完全一直运行。它似乎在我的sqlFactory.addStop函数后暂停。如果我刷新页面,它会显示我确实在推送之前通过我的sqlFactory函数正确地将它保存到我的数据库。然而,数据绑定推送本身根本不会显示在浏览器中。

我假设这是因为它仍然是一个异步功能?是否有任何方法可以使推送工作正常,或者在完成后从getJSON调用中正确地获取数据?或者甚至只是页面刷新功能?

1 个答案:

答案 0 :(得分:0)

尝试使用$ q provider

vm.getCoords(vm.newStop.name, function (result) {
    console.log("Trying to use this callback: ");
    console.log(result);
    // callback worked? continue from here
    $q.all(sqlFactory.addStop(vm.newStop.name, result.lat, result.lng, vm.newStop.stopDate, vm.tripNum))
    .then(function (result) {
        var newStop = result[0];
        vm.stops.push({
            id: parseInt(newStop.id),
            name: String(newStop.name),
            latitude: result.lat,
            longitude: result.lng,
            stopDate: new Date(vm.newStop.stopDate),
            tripNum: parseInt(newStop.tripNum)
        });
    });

});