0
我不知道如何爲json文件創建服務並在我的控制器中調用此服務。 我的應用程序中有一個控制器,因此必須保留。如何在AngularJS中使用單個控制器應用程序的json文件
我不知道如何爲json文件創建服務並在我的控制器中調用此服務。 我的應用程序中有一個控制器,因此必須保留。如何在AngularJS中使用單個控制器應用程序的json文件
嘗試通過run code snippet
藍色按鈕來運行這個例子。
基本上,您需要聲明該服務,通過Angular.DI
要求它最後調用服務方法並等待其結果。 希望它可以幫助
angular
.module('test', [])
.constant('API' , 'https://jsonplaceholder.typicode.com')
.service('TestService', function(API, $http) {
this.getData = function() {
return $http
.get(API + '/photos')
.then(function(response) {
return response.data;
})
};
})
.controller('TestCtrl', function($scope, TestService) {
//But a Resolve is preferred
TestService
.getData()
.then(function(data) {
$scope.album = data;
})
;
})
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
<article ng-controller="TestCtrl">
<div ng-repeat="photo in album">
<h3 ng-bind="photo.title"></h3>
<img ng-src="{{photo.thumbnailUrl}}" />
</div>
</article>
</section>
您必須從您的控制器呼叫您的服務。
您服務:
angular.module('YOURAPP')
.service("userAService", function ($http) {
this.promise= function() {
return $http.get('resources/json/data.json')
}
});
然後在你的控制器功能:
mycontroller = function(userAService){
userAService.promise().then(
function(response){
//do what you want in your promise
// try console.log(response.data) to see if you get your data.
}
)
}
你什麼錯誤? – Weedoze
我沒有錯誤,我沒有查看我的屏幕上的json文件內容。 – user6018902
你在哪裏調用'userAService'和'getUserData'? – Weedoze