我的服务定义如下:
module.factory('portfolio',function(){
var data;
var selectedPort;
return{
getData: function(){
return data;
},
setData:function(portfolios){
data = portfolios;
},
getSelectedPort:function(){
return selectedPort;
},
setSelectedPort:function(portfolioDetail){
selectedPort = portfolioDetail;
}
}
});
在我的控制器中代码如下:
module.controller('portfoliosController', function($scope,$http, alertService,stockService, userDataService, portfolio){
var req = {
method: 'get',
url: 'www.facebook.com',
headers: {
'Authorization': userDataService.getToken()
}
};
$http(req).then(function(reponse){
$scope.portfoliosPriceList = reponse['data'];
portfolio.setData($scope.portfoliosPriceList);
console.log(portfolio.getData())//At here,I can get the portfolio's data
}, function(){
alertService.setMessge("System maintenance , please try again later");
alertService.alert();
});
console.log(portfolio.getData())//At here, I cannot get the portfolio's data
});
错误是
Error: undefined is not an object (evaluating 'message.substr')
任何人都可以帮我解决这个问题吗?其实我真的不明白,为什么我不能得到$ http以外的数据
答案 0 :(得分:1)
这是因为javascript是异步的,所以代码:
portfolio.getData()
可能在从服务返回数据之前执行。
在这种情况下,您应该只在请求完成后(在$ http的.then()函数内)使用投资组合的数据或者设置一个承诺。
以下是有角度承诺的文档: https://docs.angularjs.org/api/ng/service/ $ Q
答案 1 :(得分:1)
使用$http
服务执行的请求是异步完成的,因此不会立即调用传递给.send
的回调。
后面的代码(console.log
)在$http(req)
调用之后但在响应请求时调用回调之前执行。
也许你会通过一个更简单的例子更好地理解:
function portfoliosController() {
var data = 'Initial Data. ',
content = document.getElementById('content');
// setTimeout would be your $http.send(req)
// calledLater would be your .then(function() { ... })
setTimeout(function calledLater() {
data = 'Data coming from the server takes some time to arrive...';
content.innerHTML = content.innerHTML + data;
}, 1000);
content.innerHTML = content.innerHTML + data;
}
portfoliosController();
<div id="content">