Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 服务功能中的AngularJS$资源_Javascript_Angularjs_Cordova_Angularjs Service_Angularjs Resource - Fatal编程技术网

Javascript 服务功能中的AngularJS$资源

Javascript 服务功能中的AngularJS$资源,javascript,angularjs,cordova,angularjs-service,angularjs-resource,Javascript,Angularjs,Cordova,Angularjs Service,Angularjs Resource,我在一个团队中工作,该团队正在使用web技术(angular.js等)和Phonegap构建一个Android应用程序,以将该项目转化为一个Android应用程序。我们是AngularJS的新手,在将服务集成到代码中时遇到了问题。我们正在尝试做一些基本的服务器调用,这些调用作为常规代码工作,但是我们正在尝试将它们作为一种服务,这样我们就不会到处重复这些调用。我们使用Phonegap localStorage插件将数据库对象的ID存储在手机的HTML5本地存储上 这是我们的代码: .service

我在一个团队中工作,该团队正在使用web技术(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事件,当应用程序加载到用户的手机上时触发。我们希望在几个控制器中调用这些服务,但最初也是在运行函数期间调用


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

希望这能帮助您走上正确的道路:

  var app = angular.module("app", ["ngResource"]);

  app.service("contactServer", function($resource, $http) {
      // Initialize resource and modify methods s.t. create POSTS and save PUTS.
      var baseUrl = "test";
      var model = {
        userName: "",
        position: ""
      }

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

      this.post = function() {
          alert("Starting post");
          var item = {"name": model.userName, "position": model.position};
          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")};
          serverResource.save(item).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]));
          })
      }
  });

  app.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();
          }

      }

  });
为了使它更好一点,我将从服务
contactServer
返回
serverResource
对象,并在控制器和运行块中使用资源的save和create方法(也在那里)


简而言之:您只需使用
$resource()
(外部服务函数声明)创建一次
$resource
,然后在函数中使用它。也不需要新的关键字,这可能是打破这一局面的原因。

希望这能帮助您走上正确的道路:

  var app = angular.module("app", ["ngResource"]);

  app.service("contactServer", function($resource, $http) {
      // Initialize resource and modify methods s.t. create POSTS and save PUTS.
      var baseUrl = "test";
      var model = {
        userName: "",
        position: ""
      }

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

      this.post = function() {
          alert("Starting post");
          var item = {"name": model.userName, "position": model.position};
          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")};
          serverResource.save(item).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]));
          })
      }
  });

  app.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();
          }

      }

  });
为了使它更好一点,我将从服务
contactServer
返回
serverResource
对象,并在控制器和运行块中使用资源的save和create方法(也在那里)


简而言之:您只需使用
$resource()
(外部服务函数声明)创建一次
$resource
,然后在函数中使用它。也不需要新的关键字,这可能是打破这一局面的原因。

您不需要更改吗

serverResource.create(item).then(function(data, status, headers, config) {...}
进入


在“信用卡资源”示例的末尾,您不需要更改吗

serverResource.create(item).then(function(data, status, headers, config) {...}
进入


在“信用卡资源”示例的末尾,您遇到的问题是方法的定义 改变这个

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

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

因此,由于您的方法是非Get实例,您应该按照以下方式执行它们:

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

HTTP获取“类”操作:Resource.action([parameters]、[success]、[error])

非获取“类”操作:Resource.action([parameters]、postData、[success]、[error])

非获取实例操作:实例.$action([参数],[成功],[错误])

我鼓励您使用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!');
            });
        }

    }
});

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

您遇到的问题是方法的定义 改变这个

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

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

因此,由于您的方法是非Get实例,您应该按照以下方式执行它们:

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

HTTP获取“类”操作:Resource.action([parameters]、[success]、[error])

非获取“类”操作:Resource.action([parameters]、postData、[success]、[error])

非获取实例操作:实例.$action([参数],[成功],[错误])

我鼓励您使用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!');
            });
        }

    }
});

…或类似的东西。希望这有帮助。

实际上这是一个有趣的问题

作为解决方法,如果您想要构建可重用的实例来进行http查询,我建议您使用restanglar。在这种情况下,它有一些优点: -它使用promise,而不是返回空对象并用新数据填充它。(这实际上是ngResource的行为)。因此,您可以在解析部分中重用您的服务。 -您不必为每个请求创建一个$resource对象。 -支持很多http方法

下面是一个例子:

角度.module('app').service('accountService'函数(重新设置角度){


您可以在这里找到更多信息。

实际上,这是一个有趣的问题

作为解决方法,如果您想构建可重用的http查询实例,我建议您使用Restanglar。在这种情况下,它有一些优点: -它使用promise,而不是返回空对象并用新数据填充它。(这实际上是ngResource的行为)。因此,您可以在解析部分重用您的服务。 -您不必为每个请求创建一个$resource对象。 -支持很多http方法

下面是一个例子:

角度.module('app').service('accountService'函数(重新设置角度){


您可以在这里找到更多信息。

模型在文件的另一部分声明,它是AngularJS的MVC框架的一部分。它的范围包括服务。@eugene1832是的,对不起,没有注意到注释。您收到的错误消息是什么?没有错误消息。我只是收到了我在“创建”之前输入代码的警报资源。然后我的应用程序的其余部分没有加载,这意味着警报后的某个部分不起作用,因此我的代码停止处理。我确定我使用$resource的方式不正确,但我使用$resource的依据是一本书和互联网资源,因此如果答案在那里,我会删除。@eugene1832,希望编辑后的答案有帮助。快速测试:.model在文件的另一部分声明,它是AngularJS的MVC框架的一部分