2016-07-10 6 views
0

を通過せずにGET呼び出して使用することはできます私の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アプリを使用する方法は、サービス内の関数に '$ scope'を渡すことなく取得できますか?

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

コントローラで::この(私はこれを試してみましたが、動作しない)のような例えば

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

私は、あなたが 'success'関数の代わりに' then'を使うことをお勧めします。 http://blog.ninja-squad.com/2015/05/28/angularjs-promises/とhttps://www.peterbe.com/plog/promises-with-$httpをご覧ください –

答えて

0

はい、あなたはそれがコントローラにせず$httpサービスを利用することができます。
サービスまたは工場でhttpコールを発信できます。

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) { 
     ... 
    }); 
    } 

}); 
関連する問題