我使用node,express,mongoose作爲後端和angular js作爲前端。我正在使用表單發送發佈請求。如何使用Angular JS獲得POST請求的響應?
<div class="alert alert-success" ng-show="success">
{{success}}
</div>
<div class="alert alert-danger" ng-show="error">
{{error}}
</div>
<form id="newCategory" ng-submit="submit()">
<div class="row">
<div class="col-md-4">
{{mySubmit}}
<div class="form-group">
<input id="name" name="name" type="text"
placeholder="Name" class="form-control input-md"
ng-model="catName">
</div><!-- ./form-group -->
</div><!-- ./col -->
<div class="form-group">
<input type="submit" name="submit" value="submit" class="btn btn-primary">
</div><!-- ./form-group -->
</div><!-- ./row -->
</form>
其操控:
fetchModule.controller('CatsNewCtrl', ['$scope', '$rootScope', 'Request',
function($scope, $rootScope, Request) {
// Root Scope
$rootScope.heading = 'Categories';
$rootScope.heading2 = 'new';
$rootScope.newLink = undefined;
$scope.catName = "";
$scope.submit = function() {
Request.post('/category', { name : $scope.catName })
.then(function(data) {
$scope.success = data.msg;
})
.catch(function(status) {
$scope.error = "Error: " + status;
});
return false;
};
}]);
的結果是什麼,我不知道我要去哪裏錯了!該服務工作正常,實際上我能夠控制檯記錄結果,但我無法將其設置爲範圍。
(function() {
let fetchModule = angular.module('fetchModule', []);
/**
* A Service for Requests.
*/
fetchModule.service('Request', ['$http', function($http) {
/**
* Get's content of a specific URL.
* @param {String} url - URL to GET.
* @return {Promise} Promise resolves with contents or rejects with an error.
*/
this.get = function(url) {
// Promise
return new Promise((resolve, reject) => {
$http.get(url)
.success(result => {
resolve(result);
})
.error((err, status) => {
reject(err);
});
});
};
/**
* Get's content of a specific URL.
* @param {String} url - URL to GET.
* @param {String} data - Data to post.
* @return {Promise} Promise resolves with contents or rejects with an error.
*/
this.post = function(url, data) {
// Promise
return new Promise((resolve, reject) => {
$http.post(url, data)
.success((data, status, headers, config) => {
resolve(data);
})
.error((data, status, headers, config) => {
resolve(status);
});
});
};
請幫助我只是一個角度的起動器。
成功方法的回調有數據是不是你想要的? – user93
這是!沒有問題,但我無法看到警報的結果 –
你可以console.log(data.message)並檢查而不是data.msg? – Ved