Javascript ng模型未因$http调用而更新
我尝试更新ng模型值作为$http.get调用的结果,但没有更新 这是我的密码 main.jsJavascript ng模型未因$http调用而更新,javascript,angularjs,Javascript,Angularjs,我尝试更新ng模型值作为$http.get调用的结果,但没有更新 这是我的密码 main.js angular.module('app', []) .controller('mainCtrl', ['$http', function($http) { var main = this; main.show = true; $http({ method: 'GET', url: 'api url' }) .then(fun
angular.module('app', [])
.controller('mainCtrl', ['$http', function($http) {
var main = this;
main.show = true;
$http({
method: 'GET',
url: 'api url'
})
.then(function(res) {
main.show = true;
console.log('succeed call, main.show: ' + main.show);
}, function(res) {
main.show = false;
console.log('failed call, main.show: ' + main.show);
});
console.log('out of call, main.show: ' + main.show);
}]);
index.html
...
<body ng-app='app' ng-controller='mainCtrl as main'>
<a ng-show='main.show' href='/'>Succeed</a>
<a ng-hide='main.show' href='/'>Failed</a>
</body>
...
api失败时的控制台日志
out of call, main.show: true
succeed call, main.show: true
out of call, main.show: true
failed call, main.show: false
我的问题是html总是显示“成功”链接
我尝试了很多东西,甚至使用了$timeout
,$apply
,但它也不起作用
类似的问题也有一些答案,但对我来说不起作用
我应该怎么做才能解决这个问题?您进行http调用的方式是错误的 首先在控制器中:
.controller('mainCtrl', ['$http', function($http) ...
在控制器中,第一个http应作为字符串传递:“$http”
异步调用按以下方式进行:
var promise = $http({
method : 'POST',
url : baseUrl,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
},
data : data
});
promise.then(function (response) {
yourData = response.data;
console.log(response.data);
return yourData;
})
.catch(function (error) {
console.log("Something went terribly wrong.");
});
将main.show初始值设置为false main.show =false; main.show=false
在上面的代码console.log('out of call,main.show:'+main.show')中,在HTML标记中定义ng应用程序值;在执行http请求之前打印,这就是您总是收到main.show=true的原因。 如果希望访问main.show,则应始终在http请求成功或失败后执行
var main = this;
main.show = true;
$http({
method: 'GET',
url: 'url'
})
.then(function(res) {
main.show = true;
console.log('succeed call, main.show: ' + main.show);
}, function(res) {
main.show = false;
console.log('failed call, main.show: ' + main.show);
DoSomething();
});
function DoSomething(){
console.log('out of call, main.show: ' + main.show);
}
一切正常 试试下面的例子。我故意指向错误的URL,因此服务调用将失败,最终将进入失败回调 演示
angular.module('app',[])
.controller('mainCtrl',['$http',函数($http){
var main=这个;
main.show=true;
$http({
方法:“GET”,
网址:'http://jsonplaceholder.typicode.com/photos1'
})
.然后(功能(成功){
main.show=true;
log('successcall,main.show:'+main.show');
},函数(错误){
main.show=false;
console.log('调用失败,main.show:'+main.show);
});
log('out of call,main.show:'+main.show);
}]);代码>
当api失败时,为什么要记录成功调用,。。。?根据代码,应该记录失败的呼叫,是吗?对不起。这是我的错误。我会编辑的。控制台有错误吗?有。控制台中的任何错误。我的意思是,浏览器控制台中是否记录了任何错误。如果是,请发布您收到的错误。哎呀。。对不起$http注入是我的输入错误。我将编辑我的问题。我用.catch编辑了我的代码,但它不能正常工作。是的,我知道。console.log('out-of-call,main.show:'+main.show));只是为了测试。这与结果无关。谢谢你的回答。使用$http和ng init是我的错。谢谢你提醒我。