HTML代码:
<div ng-controller="teamWiseResults as tr">
<p>{{tr.fifteenData.data}}</p>
<p>{{tr.fifteenData.data.name}}</p> <!--Prints the data and name within data perfectly-->
</div>
财务主任:
footieApp.controller("teamWiseResults",['yearFifteenData','yearSixteenData',function(yearFifteenData,yearSixteenData){
var main = this;
main.fifteenData = yearFifteenData;
console.log(main.fifteenData); //Prints perfectly on the console with the property "data" within it
console.log(main.fifteenData.data); //Prints undefined even though it has the property "data" within it
}]);
服务:
var footieApp = angular.module("footieApp", [])
.service('yearFifteenData', function($http) {
var main=this;
$http({
method: "GET",
url: "https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.json"
}).then((response) => {
main.data = response.data;
}, (response) => {
main.data = response.statusText;
});
console.log(main); //Prints the object perfectly, which has the property "data" within.
console.log(main.data); //Gives undefined
return main;
});
所发生的情况是,当我在控制器中使用服务"yearFifteenData“时,会正确地调用http,并给出包含属性数据的响应。我从响应中使用这些数据,并将其传递给使用它的控制器。这些控制器可以从服务访问返回的对象,但不能访问它的属性。
资源库的链接:https://github.com/spramod49/PL-football-data-app
提前感谢!
发布于 2017-11-12 00:40:44
为你服务
您必须考虑到这些.then()
函数异步运行的事实,这意味着main.data
的赋值将在调用console.log之后进行。
那么,这应该是可行的:
var footieApp = angular.module("footieApp", [])
.service('yearFifteenData', function($http) {
var main=this;
$http({
method: "GET",
url: "https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.json"
}).then((response) => {
main.data = response.data;
console.log(main.data); //Should not give undefined
}, (response) => {
main.data = response.statusText;
});
console.log(main); //Prints the object perfectly, which has the property "data" within.
return main;
});
在你的控制器里
尝试将这些console.log()
放在$timeout中,因为main.fifteenData.data是在http调用之后定义的,这可能需要几秒钟:
footieApp.controller("teamWiseResults",['yearFifteenData','yearSixteenData', '$timeout',function(yearFifteenData,yearSixteenData, $timeout){
var main = this;
main.fifteenData = yearFifteenData;
$timeout(() => console.log(main.fifteenData.data), 2000);
console.log(main.fifteenData); //Prints perfectly on the console with the property "data" within it
}]);
再次,您必须“等待服务中的承诺(即.then()
)完成。
https://stackoverflow.com/questions/47239786
复制相似问题