【问题标题】:Callback not working with Angularjs?回调不适用于Angularjs?
【发布时间】:2018-04-07 13:54:30
【问题描述】:

我不熟悉 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 调用中正确取回数据?或者甚至只是一个页面刷新功能?

【问题讨论】:

  • 用户$http服务调用webservice。如果您的 sqlFactory.addStop() 函数是异步的,那么您应该从函数返回 promise 并将值分配给 vm.stops

标签: javascript jquery angularjs getjson asynccallback


【解决方案1】:

尝试使用 $q 提供者

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)
        });
    });

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多