![](/img/trans.png)
[英]AngularJS UI-Router: preload $http data before app loads
[英]Angularjs $http get loads null data
我創建了單獨的服務和控制器,並將它們注入到htapp模塊中
我想獲取要在html頁面中顯示的url中的消息,但我從js腳本獲取了空值,並且它在html頁面中顯示了null
angular.module('htapp', []).service('testService',testService).controller('TestCtrl', TestCtrl); function TestCtrl(testService, $log) { self.getMessage = function() { testService.get() .then(function(message) { $log.info(message); self.message = message; }) } } //serivce method function testService($http, $log) { this.get = function() { return $http({ url: 'test-routes.herokuapp.com/test/hello', method: 'get' }) .then(function successCallback(res) { return res.data.message; }, function errorCallback(res) { return res.data; }) $log.info(res); } }
<!--HTML CODE--> <div ng-app="htapp"> <div ng-controller="TestCtrl as test">{{test.message}} </div> </div>
angular.module('htapp', []).service('testService',testService).controller('TestCtrl', TestCtrl);
function TestCtrl(testService, $log) {
var test = this;
test.getMessage = function() {
testService.get()
.then(function(message) {
$log.info(message);
self.message = message;
})
}
}
//serivce method
function testService($http, $log) {
this.get = function() {
return $http({
url: 'test-routes.herokuapp.com/test/hello',
method: 'get'
})
.then(function successCallback(res) {
return res.data.message;
}, function errorCallback(res) {
return res.data;
})
$log.info(res);
}
}
的HTML
<div ng-app="htapp">
<div ng-controller="TestCtrl as test">{{test.message}}
</div>
</div>
在這里閱讀更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.