gpt4 book ai didi

javascript - 将服务文件中接收到的Rest数据发送到 Controller angularjs

转载 作者:行者123 更新时间:2023-12-03 07:44:40 25 4
gpt4 key购买 nike

我是 Angular js 新手,在将接收到的数据从我的服务文件发送到 Controller 时遇到问题, Controller 最终绑定(bind)到我的 html。有人可以帮我解决这个问题吗?谢谢。

服务文件

"use strict";

angular.module("fleetListModule").service("fleetsService",

function ($http) {
this.getTrucks = function () {
console.log("before calling webservice");
$http.get('http://localhost:8080/login/rest/truckservices/getTrucks?truckId')
.success(function (data){
var trucks = data;
console.log("after calling webservice my data is", trucks);
return trucks;
});

};
});
<小时/>

Controller

"use strict";

angular.module("fleetListModule").controller("fleetListController",
['$scope', 'fleetsService',
function ($scope, fleetsService) {

var truckData = fleetsService.getTrucks();
console.log("inside fleet service", truckData);
$scope.trucks = truckData;
console.log("outside fleet service", truckData);
}]);
<小时/>

html

<div class="panel1 panel-primary">
<div class="panel-heading" align="center">TRUCKS</div>
<table class="table table-condensed table-striped " >
<thead class="truck-list-header">
<tr class="truck-list-header">
<th>Truck ID</th>
<th>Status</th>
<th>Dest.</th>
<th>Alerts</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="truck in trucks" ng-click="summaryData(truck)" class="truck-list-body">
<td>
<div><i class="fa fa-truck truck-icon"></i>{{truck.truckId}}</div>
</td>
<td>
<span class="label {{truck.label}}">{{truck.status}}</span>
</td>
<td>{{truck.destination}}</td>
<td>
<div><i class="fa fa-exclamation-triangle alert-icon"></i>{{truck.alerts}}</div>
</td>
</tr>
</tbody>
</table>
</div>
<小时/>

从localhost 8080接收json数据

{"truckId":"111","status":"Running","destination":"Winnipeg","alerts":"Nothing"}

最佳答案

您的服务函数不会返回任何内容。 success 中的 return 也没有执行任何操作

由于 success 已弃用,因此使用 then 简化了服务版本:

this.getTrucks = function() {
console.log("before calling webservice");
// return the promise created by `$http`
return $http.get('http://localhost:8080/login/rest/truckservices/getTrucks?truckId')
.then(function(responsePromise) {
var trucks = responsePromise.data;
console.log("after calling webservice my data is", trucks);
return trucks;
});

};

在 Controller 中

 fleetsService.getTrucks().then(function(truckData) {
// assign data inside promise callback
console.log("inside fleet service", truckData);
$scope.trucks = truckData;

});
// can't do this one , it will run before data has been returned from server
console.log("outside fleet service", $scope.trucks);//will be undefined

关于javascript - 将服务文件中接收到的Rest数据发送到 Controller angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35259060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com