在AngularJS中调用ajax之后执行服务 [英] execute a service after a call ajax in AngularJS
问题描述
我需要在ajax调用后将数据保存在服务工厂中.所有这些都无需location.href.但是当我输入代码$ window.location.href时,它不起作用.这是代码:
I need to save data in a service factory after a ajax call. It all works without location.href. But it doesn't work when I put the line code $window.location.href. This is the code:
scope.res = function(id){
factoryService.getLista(id,"en-US","")
.then (function(response){commonVarService.setA(response.A);
commonVarService.setB(response.B);
commonVarService.setC(response.C);
$window.location.href="./menu/menu.html";
})
.catch(function(err) {console.log(err)});
};
在这里,factoryService允许进行ajax调用,而commonVarService则允许在service变量中存储数据.如果没有$ window.location.href =",那么一切都可以,但是当有$ window.location.href时,应用程序将在新页面中重定向,而无需存储该变量.我的错误在哪里?有什么好的解决方案吗?预先感谢.
Where, factoryService allow to make an ajax call, wherease commonVarService allow to memorize data in variables of service. If there isn't the $window.location.href="" it all works, but when there is the $window.location.href, the application redirect in the new page without memorize the variable. where is it my Error? Is there some good solution? Thanks in advance.
commonVarService代码是这样的:
the commonVarService code is this:
angular.module('common_variable',[]).service('commonVarService',function(){
angular.module('common_variable',[]) .service('commonVarService',function(){
/*a*/
this.getA = function(){
return this._a;
}
this.setA = function(a){
return this._a=a;
}
/*b*/
this.getB = function(){
return this._b;
}
this.setB = function(b){
return this._b = b;
}
/*c*/
this.getC = function(){
return this._c;
}
this.setC = function(c){
return this._c = c;
}
});
我还尝试仅将字符串作为参数:
I also tried to put simply only the string as parameter:
commonVarService.setA("A");commonVarService.setB("B");commonVarService.setC("C")
commonVarService.setA("A"); commonVarService.setB("B"); commonVarService.setC("C")
但是当我进入href链接的新page.html时,变量A,B,C未定义...我不知道.
but when I'm in the new page.html of href link, the variable A , B, C are undefined...I don't know..
非常感谢!
推荐答案
所以,我在这里解释问题,当您使用 $ window.location.href ='something'
.它会刷新整个页面,因此无法存储变量,无法恢复新的角度实例.我建议使用,angular-route或angular-ui-router,您可以在其中使用this, $ location.path('/profile')
或 $ location更改路线.path('/mypage')
(如果您正在构建SPA(单页应用程序),它将保留页面状态).
So, I am explaining the problem here,
When you are using$window.location.href = 'something'
.
It does a full page refresh, so it cannot store the variable,reinstatiate a new angular instance.
i would suggest to use , angular-route or angular-ui-router , where you can change the route by using this , $location.path('/profile')
or $location.path('/mypage')
if you are building a SPA(Single page application) ,which will retain the state of your page.
这篇关于在AngularJS中调用ajax之后执行服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!