2016-09-29 40 views

回答

1

嘗試通過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>

1

您必須從您的控制器呼叫您的服務。

您服務:

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. 
     } 
    ) 
} 
相關問題