C# 我是否对此服务进行同步调用,并在controller中正确使用该服务?
我哥哥让我编写服务同步调用,但下面的代码给了我一个错误。如何才能正确地执行此操作 这是我的角度服务和控制器C# 我是否对此服务进行同步调用,并在controller中正确使用该服务?,c#,angularjs,asp.net-mvc,C#,Angularjs,Asp.net Mvc,我哥哥让我编写服务同步调用,但下面的代码给了我一个错误。如何才能正确地执行此操作 这是我的角度服务和控制器 app.service(“StateService”),函数($http,$q){ 变量工厂=$q.defer(); factory.getStateData=函数(){ 返回$http.get(“/State/GetStateData”) .然后(功能(响应){ 工厂解析(响应数据); 返厂承诺; },功能(回应){ 工厂拒绝(响应); 返厂承诺; }); }; factory.ge
app.service(“StateService”),函数($http,$q){
变量工厂=$q.defer();
factory.getStateData=函数(){
返回$http.get(“/State/GetStateData”)
.然后(功能(响应){
工厂解析(响应数据);
返厂承诺;
},功能(回应){
工厂拒绝(响应);
返厂承诺;
});
};
factory.getCountryById=函数(Id){
返回$http.post('/Country/GetCountryById?Id='+Id)
.然后(功能(响应){
工厂解析(响应数据);
返厂承诺;
},功能(回应){
工厂拒绝(响应);
返厂承诺;
});
};
};
app.controller(“statecontroller”,函数($scope,StateService,$http,$timeout){
//获取函数
$scope.GetStateData=函数(){
StateService.getStateData().then(函数(d){
$scope.States=d.data;
$scope.fillAllData();
},功能(回应){
警报('发生错误'+响应.data.ExceptionMesage);
});
};
$scope.fillAllData=函数(){
对于(变量i=0;i<$scope.States.length;i++){
if($scope.States[i].CountryId)
{
//var val=$scope.GetCountryById($scope.States[i].CountryId);
var cName=“”;
var Id=$scope.States[i].CountryId;
StateService.getCountryById(Id).then(函数(d){
如果(d.数据)
cName=d.data.CountryName;
},功能(回应){
console.log('发生错误'+响应.data.ExceptionMesage);
});
$scope.States[i].CountryName=cName;
}
其他的
$scope.States[i].CountryName=null;
}
}
}
您确定要进行同步调用吗?同步调用会在等待响应时停止浏览器,而这几乎永远都不是您想要的。我想您实际上指的是异步
您可能误解了服务的工作原理。它基本上只是Angular注入的单例对象。此外,$http
-服务已经为您创建了承诺,因此您可以通过这样编写来大幅简化服务器:
app.service("StateService", function ($http) {
var service = this;
service.getStateData = function () {
return $http.get("/State/GetStateData");
};
service.getCountryById = function (Id) {
return $http.post('/Country/GetCountryById?Id=' + Id);
};
};
app.controller("statecontroller", function ($scope, StateService, $http, $timeout) {
// get function
$scope.GetStateData = function () {
$scope.States = StateService.getStateData();
$scope.fillAllData();
};
...
});
这应该与控制器中的实现配合得很好
同步方法-但实际上,不要这样做
然后在控制器中按如下方式使用它:
app.service("StateService", function ($http) {
var service = this;
service.getStateData = function () {
return $http.get("/State/GetStateData");
};
service.getCountryById = function (Id) {
return $http.post('/Country/GetCountryById?Id=' + Id);
};
};
app.controller("statecontroller", function ($scope, StateService, $http, $timeout) {
// get function
$scope.GetStateData = function () {
$scope.States = StateService.getStateData();
$scope.fillAllData();
};
...
});
剩下的就是接听用户的愤怒支持电话,他们是您阻止执行的浏览器
还请注意,同步请求可能无法在所有较新的浏览器中工作:
注意:从Gecko30.0(Firefox30.0/Thunderbird 30.0)开始/
SeaMonkey 2.27),主线程上的同步请求
由于对用户体验的负面影响,已弃用。
还有另一个不这么做的原因。我这么做了,但哥哥说要写同步调用,我不知道他为什么这么说,但我想写。请帮帮我,谢谢你的帮助。不要听你哥哥的话。他错了。根据你的用法,完全没有理由同步这么做。