2017-05-18 22 views
0

url,但我不明白如何從到的NodeJS角度的數據,在這裏我要離開我的代碼

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( '/患者/:ID')沒有接收到ID?我如何在angularjs中獲得url的id?

+1

請修復你的代碼,變量名,函數中有很多不需要的空格... – Mistalis

回答

0

在工廠中,您可以定義一個可以發出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字符串中。您可以通過檢查大多數瀏覽器開發人員工具中的網絡選項卡來確認。

0

您需要自己發送該ID作爲請求中網址的一部分。在角度上,您目前正在向/patient/:id發送請求。嘗試用角碼中的:id替換數據庫中患者的有效標識。例如:

$http.get('/patient/12') 
    .then(function (res) {...}) 

12應該再顯示爲您req.param.id在你的服務器端代碼。

我還建議您遵循user2263572的建議,並將此邏輯封裝到工廠中。