的HTML代码:无法访问在angularjs控制器的对象的属性,但能够从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被正确调用,并且gi在其中有属性数据的响应。我使用响应中的这些数据并将其传递给使用它的控制器。这些控制器能够从服务访问返回的对象,但无法访问它的属性。该程序存储库的
链接:https://github.com/spramod49/PL-football-data-app
提前感谢!
你的'main.data'只有在承诺解析发生的时候才会被一个值填满(即then()),直到那时它是未定义的,如果你需要进一步处理这个数据也许这将是一个很好的想把它移向控制器 –
可以请你分享你在main.fifteenData和main中获得的数据吗? –
@RakeshBurbure可以在代码中的http调用的URL中找到数据。 –