[英]How get acces to response.data value in AngularJS?
我想通過http請求在組件中設置數據,但是$ http.get之外的數據未定義。
如何在$ http.get之外獲取響應數據?
'use strict';
angular.
module('filesApp').
component('filesList', {
template:
'<ul>' +
'<li ng-repeat="file in $ctrl.files">' +
'<span>{{file.data1}}</span>' +
'<p><a href="{{file.data2}}">Create</a></p>' +
'</li>' +
'</ul>',
controller: function FilesListController($http, $scope) {
//need response.data here
$http.get('/api/1').then(function (response) {
if (response.data.error) {
return null;
} else {
$http.get('/api/2' + response.data).then(function (response) {
if (response.data.error) {
return null;
} else {
//response.data contains data that I need.
return response.data;
}
});
}
});
}
});
您需要在范圍上存儲response.data
,以便可以在視圖中使用它。
'use strict';
angular.module('filesApp')
.component('filesList', {
template:
'<ul>' +
'<li ng-repeat="file in $ctrl.files">' +
'<span>{{file.data1}}</span>' +
'<p><a href="{{file.data2}}">Create</a></p>' +
'</li>' +
'</ul>',
controller: function FilesListController($http, $scope) {
$http.get('/api/1').then(function (firstResponse) {
if (firstResponse.data.error) {
return null;
} else {
$http.get('/api/2' + firstResponse.data).then(function (secondResponse) {
if (secondResponse.data.error) {
return null;
} else {
$scope.files = secondResponse.data;
}
});
}
});
}
});
有很多方法可以做到這一點。 當然,最簡單的方法是將響應數據存儲在范圍內的變量中。 例如
controller: function FilesListController($http, $scope) {
//need response.data here
$http.get('/api/1').then(function (response) {
if (response.data.error) {
return null;
} else {
$http.get('/api/2' + response.data).then(function (response) {
if (response.data.error) {
return null;
} else {
//response.data contains data that I need.
$scope.dataYouNeed = response.data;
}
});
}
});
}
您可以使用{{dataYouNeed}}
在視圖中的某個位置顯示它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.