gpt4 book ai didi

javascript - 如何获取我的示例中的http请求数据?

转载 作者:行者123 更新时间:2023-12-03 11:32:02 26 4
gpt4 key购买 nike

我正在尝试在我的第一个 Controller 中获取http请求结果。 http 请求由另一个 Controller 触发。我遇到的问题是我不确定如何检测请求是否在我的第一个 Controller 中完成。我有类似的东西

第一个 Controller :

//I am not sure how to get the customer result if
//http requests are trigger by another controllers here.

customerFactory.getCustomerResult????

第二个 Controller :

//trigger the http request..
var id = 1;
$scope.clickme = function() {
var obj = customerFactory.callApi(id)
}

我的工厂

customerFactory.callApi = function(id) {
return getCustomer(id)
.then(function(customer) {
return customer;

})
}

var getCustomer = function(id) {
return $http.get('/api/project1/getCustomer' + id);
}

return customerFactory;

html

<div ng-controller="firstCtrl">
//codes...
</div>

//other codes..
//other codes..

<div ng-controller="secondCtrl">
//codes...
</div>

第一和第二 Controller 不相关。他们彼此相距很远。如何让firstCtrl检测http请求完成并获取客户数据?非常感谢!

最佳答案

您可以使用工厂或单例服务来负责发出请求和存储数据。服务和工厂都是单例,因此单个实​​例在应用程序的执行中持续存在,并且可以通过注入(inject)工厂或服务从 Controller 引用数据和函数(这两种方式都是在配置之前使用更简洁的语法定义提供者的方法)不需要通过提供商使用服务/工厂)。

angular.module("exampleApp", []).service('ExampleService', ["$http", "$q" ,function ($http, $q) {
var service = {
returnedData: [],
dataLoaded:{},
getData = function(forceRefresh)
{
var deferred = $q.defer();

if(!service.dataLoaded.genericData || forceRefresh)
{
$http.get("php/getSomeData.php").success(function(data){
angular.copy(data, service.returnedData)
service.dataLoaded.genericData = true;
deferred.resolve(service.returnedData);
});
}
else
{
deferred.resolve(service.returnedData);
}

return deferred.promise;
},
addSomeData:function(someDataToAdd)
{
$http.post("php/addSomeData.php", someDataToAdd).success(function(data){
service.getData(true);
});
}
};
return service;
}]).controller("ExampleCtrl", ["$scope", "ExampleService", function($scope, ExampleService){
$scope.ExampleService = ExampleService;
}]).controller("ExampleCtrl2", ["$scope", "ExampleService", function($scope, ExampleService){
ExampleService.getData();
$scope.ExampleService = ExampleService;
}]);

关于javascript - 如何获取我的示例中的http请求数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26695410/

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