javascript - 服务函数中的 AngularJS $resource

标签 javascript angularjs cordova angularjs-service angularjs-resource

我所在的团队正在使用网络技术(angular.js 等)和 Phonegap 构建 Android 应用程序,以将项目转变为 Android 应用程序。我们是 AngularJS 的新手,在将服务集成到我们的代码中时遇到了问题。我们正在尝试执行一些基本的服务器调用,这些调用作为常规代码工作,但我们正在尝试使它们成为一项服务,因此我们不会在所有地方重复它。我们使用 Phonegap localStorage 插件将数据库对象的 ID 存储在手机的 HTML5 本地存储中。

这是我们的代码:

.service("contactServer", function($resource, $http, baseUrl) {
    // Initialize resource and modify methods s.t. create POSTS and save PUTS.
    this.post = function() {
        alert("Starting post");
        var item = {"name": model.userName, "position": model.position};
        alert("Creating resource");
        var serverResource = $resource(baseUrl,
            {create: {method: "POST"}, save: {method: "PUT"}});
        alert("Created resource");
        new serverResource.create(item).then(function(data, status, headers, config) {
            alert("id: " + data._id);
            window.localStorage.setItem("DBid", data._id);
        }, function(data, status, headers, config) {
            alert(JSON.stringify(['Error', data, status, headers, config]))
        })
    }

    this.put = function() {
        alert("Starting put");
        var item = {"name": model.userName, "position": model.position, "id": window.localStorage.getItem("DBid")};
        alert("Creating resource");
        var serverResource = $resource(baseUrl + "/:id", {id: "@id"},
            {create: {method: "POST"}, save: {method: "PUT"}});
        alert("Created resource");
        new serverResource(item).save().then(function(data, status, headers, config) {
            alert(JSON.stringify(['Success', data, status, headers, config]));
        }, function(data, status, headers, config) {
            alert(JSON.stringify(['Error', data, status, headers, config]));
        })
    }
})

baseUrl 是指向我们数据库的 URL 链接。我们在这里调用服务:

.run(function(contactServer) {
    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {

        if (window.localStorage.getItem("DBid") == null) {
            alert("no DBid");
            contactServer.post();
        }
        else {
            alert("Retrieved stored DBid: " + window.localStorage.getItem("DBid"));
            contactServer.put();
        }

    }
})

deviceready 是一个 Phonegap 事件,当应用程序加载到用户手机上时会触发该事件。我们想在我们的几个 Controller 中调用这些服务,但最初也是在此运行函数期间。

代码在 run 函数中调用后触发“starting post”警报,但随后中断。我们使用 $resource 错了吗? (它被正确地列为依赖项)。我们是否错误地实现了服务?

最佳答案

你的问题是你的方法的定义 改变这个

var serverResource = $resource(baseUrl,
            {create: {method: "POST"}, save: {method: "PUT"}});

进入这个:

var serverResource = $resource(baseUrl, {},
            {create: {method: "POST"}, save: {method: "PUT"}});

看看 documentation

因此,由于您的方法不是 Get 实例,因此您应该像下面这样执行它们:

new serverResource.$create(item).then(function(data, status, headers, config) {
            //content
        }, function(data, status, headers, config) {
            //error content
        })

文档说:

HTTP GET "class" actions: Resource.action([parameters], [success], [error])

non-GET "class" actions: Resource.action([parameters], postData, [success], [error])

non-GET instance actions: instance.$action([parameters], [success], [error])

我鼓励您使用 console.log 而不是警报来调试您的代码,警报可能会在摘要循环中产生一些问题。

让我给你一个替代方案:

.factory('contactServer', ['$resource', function($resource){
    var baseUrl = 'testing/:id';
    var resource = $resource(baseUrl, {id: '@id'}, {update: {method: 'PUT'}});
    return resource;
}]);

您可以将其用作:

.run(function(contactServer) {
    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {

        if (window.localStorage.getItem("DBid") == null) {
            alert("no DBid");
            //item creation
            var instance = new contactServer(item);
            contactServer.$save(item).then(function(res){
                 window.localStorage.setItem("DBid", res._id);
            });
        }
        else {
            alert("Retrieved stored DBid: " + window.localStorage.getItem("DBid"));
            var id = //theId;
            var updateObject = //item update;
            var instance = new contactServer();
            contactServer.$update({id: id}, updateObject).then(function(res){
                console.log('object updated!');
            });
        }

    }
});

..或类似的东西。希望对您有所帮助。

关于javascript - 服务函数中的 AngularJS $resource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26555337/

相关文章:

android - 制作跨平台 RTMP 流媒体/播放应用程序的正确方法。 Phonegap livu插件?

angular - 如何修复 "Could not determine the dependencies of task ' :app:preDebugBuild'"in Ionic 4 Cordova

javascript - 如何使用 jquery 单击动态单元格值打开对话框

javascript - Google Maps V3 和 jQuery 中的 Directions API 存在问题

javascript - AngularJS 应用程序中部署服务器上的相对路径问题

python - 使用 JSON 将数据从 Angular.js POST 到 Django REST API

javascript - 未捕获的类型错误 : Function is not a function

javascript - 在javascript中用下划线替换字符串中的字母

javascript - 如何使用 AngularJS $http 发送 multipart/form-data

android - 构建 cordova 新的空项目并定位到 android-22