我想在使用网络 API 和 angular 资源创建新记录时获取新 ID
I want to get the new ID when new record is created using web API and angular resource
我正在使用 Web API 和 Angular 资源来管理我的应用程序..
在我的控制器中使用 Save 方法时,我想接收新保存的记录 ID...
我的网络 API 方法 return 响应创建消息中的新 ID.. 但我无法读取它...
这是我的服务:
'use strict';
appServices.factory('projectsService', function ($resource, ngAuthSettings) {
var serviceBase = ngAuthSettings.apiServiceBaseUri;
return $resource(serviceBase + '/api/project/:id', {}, {
get: { method: 'GET', params: { id: '' }, isArray: true },
getById: { method: 'GET', params: { id: '0' }, isArray: false },
save: { method: 'POST' ,isArray: false},
update: { method: 'PUT' },
remove: { method: 'DELETE' }
});
});
这是我的控制器方法:
$scope.save = function ($event) {
$event.preventDefault();
$('#AddProjectForm').parsley().validate();
if ($('#AddProjectForm').parsley().isValid() ) {
//HEre is my save method
projectsService.save($scope.project).$promise.then(function (newid) {
$location.path('/project/' + newid);
},
function (response) {
$scope.message = "Failed to register user due to:" + errors.join(' ');
});
}
};
在我的网站中 API 这是 return
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, projectRepository.NewID);
return response;
有什么想法吗??
您很可能从 api 传回一个 json 对象。所以,newid 可能是一个 json 对象。尝试更新此行:
$location.path('/project/' + newid);
到
$location.path('/project/' + newid.id);
此外,请确保您的 api 确实在响应中传回了 id,如果以上行对您不起作用,请检查 id 字段的 属性 名称是什么。
更新:
尝试更新您的 web.api 响应函数,使其看起来像这样:
return Request.CreateResponse(HttpStatusCode.Created, new { projectRepository.NewID });
我正在使用 Web API 和 Angular 资源来管理我的应用程序.. 在我的控制器中使用 Save 方法时,我想接收新保存的记录 ID...
我的网络 API 方法 return 响应创建消息中的新 ID.. 但我无法读取它...
这是我的服务:
'use strict';
appServices.factory('projectsService', function ($resource, ngAuthSettings) {
var serviceBase = ngAuthSettings.apiServiceBaseUri;
return $resource(serviceBase + '/api/project/:id', {}, {
get: { method: 'GET', params: { id: '' }, isArray: true },
getById: { method: 'GET', params: { id: '0' }, isArray: false },
save: { method: 'POST' ,isArray: false},
update: { method: 'PUT' },
remove: { method: 'DELETE' }
});
});
这是我的控制器方法:
$scope.save = function ($event) {
$event.preventDefault();
$('#AddProjectForm').parsley().validate();
if ($('#AddProjectForm').parsley().isValid() ) {
//HEre is my save method
projectsService.save($scope.project).$promise.then(function (newid) {
$location.path('/project/' + newid);
},
function (response) {
$scope.message = "Failed to register user due to:" + errors.join(' ');
});
}
};
在我的网站中 API 这是 return
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, projectRepository.NewID);
return response;
有什么想法吗??
您很可能从 api 传回一个 json 对象。所以,newid 可能是一个 json 对象。尝试更新此行:
$location.path('/project/' + newid);
到
$location.path('/project/' + newid.id);
此外,请确保您的 api 确实在响应中传回了 id,如果以上行对您不起作用,请检查 id 字段的 属性 名称是什么。
更新:
尝试更新您的 web.api 响应函数,使其看起来像这样:
return Request.CreateResponse(HttpStatusCode.Created, new { projectRepository.NewID });