Convert Angular HTTP.get function to a service

后端 未结 2 690
星月不相逢
星月不相逢 2020-12-07 07:01

I\'m trying to convert an Angular HTTP.get function in my controllers.js to a service in services.js.

The examples I have fo

2条回答
  •  北海茫月
    2020-12-07 07:36

    Here is an implementation of service service instead of above mentioned factory service. Hope it helps.

    app.js

    angular.module('myApp', ['controllers', 'services'])
     .config(['$routeProvider', function($routeProvider){
        $routeProvider
          .when('/bookslist', {
            templateUrl: 'partials/bookslist.html', 
            controller:  "BooksListCtrl"
          })
          .otherwise({redirectTo: '/bookslist'});
      }]);
    

    service.js

    angular.module('services', [])
      .service('books', ['$http', function($http){
          this.getData = function(onSuccess,onError){
              $http.get('books.json').then(
                  onSuccess,onError);
          }  
      }]);
    

    controller.js

    angular.module('controllers',[])
        .controller('BooksListCtrl', ['$scope', 'books', function($scope, books){
           $scope.submit = function(){
    
            $scope.books = books.getData($scope.onSuccess,$scope.onError);
           }
               $scope.onSuccess = function(data){
               console.log(data);
               $scope.bookName = data.data.bookname;
               }
    
               $scope.onError = function(error){
                   console.log(error);
               }
      }]);
    

提交回复
热议问题