[英]Controller not logging response from Nodejs using Angular $http service
我創建了一個表單和onclick表單,我希望看到服務器的響應(nosejs)。 在Angular Controller中調用服務。 從服務本身調用時,響應是可見的,但是當從控制器調用時,沒有任何顯示。
控制器:
MyApp.angular.controller("loginCtrl", function($scope, UserService){
$scope.name = "TestName";
$scope.check = function(user){
UserService.createUser(user, function(response){
$scope.userinfo = response;
console.log("FROM Ctrlr: " + response);
});
}
});
服務:
MyApp.angular.factory("UserService", function($http,$location){
var service = {
createUser: createUser
};
return service;
function createUser(user){
$http.post("/register", user).then(function(response){
console.log("FROM Srvc:" +response);
});
}
});
的NodeJS:
app.post("/register", function(req, res){
var user = req.body;
res.json(user);
});
如果我從服務中調用響應,我可以看到響應記錄到控制台。 但是從控制器本身調用時沒有響應。 包含MyApp.angular.factory
和MyApp.angular.controller
原因是我在另一個配置文件中聲明了MyApp。
我究竟做錯了什么?
為了從工廠獲得控制器中的響應,請在工廠中更改createUser
func,如下所示:
function createUser(user){
//notice the return here!!!
return $http.post("/register", user).then(function(response){
console.log("FROM Srvc:" +response);
return response.data; //notice the return here too!!!
});
}
你需要在函數內部返回promise, then
返回結果,以便從你調用函數的任何地方訪問它。
與使用基於回調的API的node.js不同,AngularJS框架使用基於承諾的API。 返回promise並使用其.then
方法:
app.controller("loginCtrl", function($scope, UserService){
$scope.name = "TestName";
$scope.check = function(user){
//UserService.createUser(user, function(response){
//USE .then method
return UserService.createUser(user).then(function(data) {
$scope.userinfo = data;
console.log("FROM Ctrlr: " + data);
return data;
}).catch(function(errorResponse) {
console.log(errorResponse.status);
throw errorResponse;
});
}
});
function createUser(user){
var promise = $http.post("/register", user).then(function(response){
var data = response.data;
console.log("FROM Srvc:" +data);
//RETURN data to chain
return data;
});
//RETURN promise
return promise;
}
不要將基於承諾的API轉換為回調類型的API。 它被認為是一種反模式。
您需要再添加1個參數,回調並將響應返回給回調函數
function createUser(user, callback){
$http.post("/register", user).then(function(response){
console.log("FROM Srvc:" +response);
callback(response); // return the response in the callback function
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.