[英]How to use $ http.get () of angularjs 1.6 with url with parameters
我正在使用nodejs和angularjs,但是我不明白如何將數據從nodejs轉換為angularjs,我將把代碼留在這里
App.js角度
Var myApp = angular.module ('angularTodo', ['angularUtils.directives.dirPagination']);
MyApp.controller ('mainController', ['$ scope', '$ http', function ($ scope, $ http) {
$ Http.get ('/ api / all'). Then (function (res) {
$ Scope.pacientes = res.data;
$ Scope.sort = function (keyname) {
$ Scope.sortKey = keyname; // set the sortKey to the param passed
$ Scope.reverse =! $ Scope.reverse; // if true make it false and vice versa
}
}). Finally (function () {
$ Scope.example7 + = "(Finally called)";
});
}]);
MyApp.controller ('patient', ['$ scope', '$ http', function ($ scope, $ http)
$ Http.get ('/ patient /: id') .then (function (res) {
$ Scope.new = res.data.pk;
$ Scope.test = "test11";
}). Finally (function () {
$ Scope.example7 + = "(Finally called)";
});
}]);
Routes.js
App.get ('/ patient /: id', function (req, res) {
Var id = req.params.id;
Connection.query ('SELECT * FROM patient WHERE pat_id =?', [Id], function (err, data)
{
If (err)
Console.log ("Error Selecting:% s", err);
Res.json (data [0]);
Console.log (id);
Console.log (data);
});
});
App.get ('/ newinf /: id', isLoggedIn, function (req, res) {
Res.render ('informe.ejs', {user: req.user});
});
問題是$ http.get('/ Patient /:id')沒有收到ID? 如何在angularjs中獲取URL的ID?
在工廠中,您可以定義一個發出http請求的函數。
MyApp.factory('test_factory',function($http,{
factory = {};
factory.get_request = function(params){
return $http({
method: 'GET',
url: 'some_url',
params: params
})
};
return factory
});
在您的控制器中,您可以發出在工廠中定義的http請求(確保對工廠進行DI)。 注意我如何將對象傳遞給工廠內的get_request函數。
MyApp.controller('some_ctrl',function($scope,test_factory){
test_factory.get_request({id:12345}).then(function(data){
console.log(data)
})
});
當然,您可以使用基本相同的語法直接從控制器發出http請求。 但是通常最好的做法是將請求邏輯分離到工廠中。
另外,由於您正在發出GET請求,因此發出請求時,查詢參數將添加到url字符串中。 您可以通過檢查大多數瀏覽器開發人員工具中的“網絡”標簽來確認這一點。
您需要自己發送ID作為請求中URL的一部分。 在angular中,您當前正在向/patient/:id
發送請求。 嘗試將角度代碼中的:id
替換為數據庫中患者的有效ID。 例如:
$http.get('/patient/12')
.then(function (res) {...})
12應該req.param.id
在服務器端代碼中顯示為req.param.id
。
我還建議您遵循user2263572的建議並將此邏輯也封裝到工廠中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.