AngularJS服务(更新/保存)

Log*_*n W 6 javascript angularjs

AngularJS的新手,试图掌握框架,并尝试构建一个基本的CRUD应用程序.我似乎无法弄清楚更新现有记录需要什么.这是我的服务:

 angular.module('appServices', ['ngResource']).
factory('App', function ($resource) {
    var Item = $resource('App/:AppId', {
        //Default parameters
        AppId: '@id'
    }, {
        //Actions
        query: {
            method: 'GET',
            isArray: true
        },
        getById: {
            method: 'PUT'
        },
        update: {
            method: 'POST'
        }
    });
    return Item;
});
Run Code Online (Sandbox Code Playgroud)

我可以运行一个基本的Get all查询,并使用getById来填充一个编辑表单,但这就是我被困住的地方.这是getById的示例代码

 $scope.apps = App.query();

$scope.getEdit = function(AppId) {
    App.getById({id:AppId}, function(app) {
        $scope.original = app;
        $scope.app = new App(app);
    });
};

$scope.save = function() {
    //What type of information should go here?
    //Do I need to make changes to the appServices?
};
Run Code Online (Sandbox Code Playgroud)

我想,我只是不确定下一步有关更新现有信息,或者"app"对象如何传递给API,是否有人能指出我正确的方向,或者向我展示一个快速更新方法?

Odd*_*man 6

这是处理角度保存操作的一种非常混乱的方式.首先 - 您不应该将PUT操作用于检索请求,其次 - 所有这些操作都已内置于角度.见下文.

var Item = $resource( 'App/Details/:AppId', { AppId: '@id' } );

var item = Item.get({ id: 1 }, function( data ) {
    data.setAnothervalue = 'fake value';
    data.$save();
);
Run Code Online (Sandbox Code Playgroud)

我在这里做的是检索"项目",然后在返回后立即用新数据保存它.

Angular JS已经提供了一堆默认值,包括查询,保存,删除/删除,get.etc.对于大多数RESTful API,你真的不需要添加太多,如果有的话.有关更多信息,请参阅资源文档,尤其是有关默认值的信息:http://docs.angularjs.org/api/ngResource.$ resource

此外,一旦你得到了一个处理 - 你可能想要使用$ save进行创建/更新操作,但使用POST/PUT(RESTful约定).如果你这样做,请参阅我不久前写的文章:http://kirkbushell.me/angular-js-using-ng-resource-in-a-more-restful-manner/


Log*_*n W 4

在做了更多研究并查看了丹尼尔的链接之后(谢谢)。我成功了。

控制器方法:

 $scope.save = function() {
    $scope.app.update();
};
Run Code Online (Sandbox Code Playgroud)

服务工厂:

 var Item = $resource('App/Details/:AppId', {
        //Default parameters
        AppId: '@id'
    }, {
        //Actions
        query: {
            method: 'GET',
            isArray: true
        },
        getById: {
            method: 'PUT'
        },
        update: {
            method: 'POST'
        }
    });

    Item.prototype.update = function (cb) {
        console.log(this.AppId);
        return Item.update({ AppId: this.AppId },
        angular.extend({}, this, { AppId: undefined }), cb);
    };

    return Item;
Run Code Online (Sandbox Code Playgroud)