2016-07-10 33 views
0

這裏是我的service.js:

app.service('myService',['$http',function($http){ 
    this.getSomething = function($scope){ 
     return $http({ 
      method: "GET", 
      url: "...", 
      headers: {...} 
     }).success(function(response){ 
      $scope.items = response; 
     }).error(function(response){ 
      ... 
     }); 
    } 
}]); 

這裏是我的controller.js:

app.controller('myController',['$scope','myService',function($scope,myService){ 
    $scope.items = {}; 
    myService.getSomething($scope); 
}]); 

但我想知道是否有另一種使用web api的方式是在不將'$ scope'傳遞給服務中的函數的情況下獲取?然後

... 
this.getSomething = function(){ 
    return $http({ 
     ... 
    }).success(function(response){ 
     return response; 
    }).error ... 
     ... 
} 

控制器:例如像這樣(我試過,但不起作用)

... 
$scope.items = myService.getSomething(); 
+0

我建議你使用'then'而不是'success'函數。看到這個http://blog.ninja-squad.com/2015/05/28/angularjs-promises/和https://www.peterbe.com/plog/promises-with-$http –

回答

0

是的,你可以使用$http服務,而它的控制之中。
您可以將http調用放入Service或Factory中。

app.service('MyHttpService', function($http) { 
    this.getData = function(id) { 
    $http.get(<URL>, <PARAMS>).then(function(success) { 
     return success; 
    }, function(err) { 
     return err; 
    }); 
    } 
}); 

// In you Controller 

app.controller('MyCtrl', function(MyHttpService){ 
    $scope.data = getData .getData(); 
}) 

這是隻是一個簡單的例子可以讓這個MyHttpService更受回報的承諾,而不是直接將數據強勁;

0

是的,向前邁進,最好不要一般地使用$ scope,但你絕對不需要將它傳遞給服務。這通常是我如何建模我的服務/控制器。

服務:

//Using es6 syntax 
this.getData() { 
    return $http.get('/api/') 
     .then(({data}) => data) 
     .catch(({data}) => console.log('FAILED: ', data.message)); 
} 

//es5 
this.getData() { 
    return $http.get('/api/') 
     .then(function(res) { 
      return res.data 
     }) 
     .catch(function(res) { 
      console.log('FAILED: ', res.data.message)); 
     }); 
} 

控制器:

//es6 
apiService.getData() 
    .then(data => this.data = data); 

//es5 
apiService.getData() 
    .then(function(data){ 
    this.data = data; 
    }); 
0

你不應該傳遞$範圍的服務。 $ scope在控制器中用於綁定到視圖。

app.controller('myCtrl', function($scope, service) { 

    $scope.items = service.getItems(); 

}); 

app.service('service', function() { 

    this.getItems() { 
    return $http.get('/api/items') 
    .then(function(res) { 
     return res.data 
    }) 
    .catch(function(res) { 
     ... 
    }); 
    } 

}); 
相關問題