2014-02-08 4 views
1

AngularJS와 서비스에 대한 속성/메소드를 지정하는 방법 :내가 각도 서비스 만든

app.service('myService', ['$http', '$q', function($http, $q){ 
    var getInfo = function(){ 
     return $http({ 
      method: 'GET', 
      url: 'X' 
     }); 
    }; 
}]); 

및 컨트롤러를 recognice하지 않습니다

app.controller('myController', ['$scope', 'myService', function ($scope, myService) { 


    myService.getInfo() 
    .success(function(data, status, headers) { 

    }) 
    .error(function(data, status, headers) { 

    }) 

}]); 

내가이 얻을 콘솔의 오류 :

TypeError: Object [object Object] has no method 'getInfo' 

무엇이 실종 되나요?

답변

3

Tthat는 this.getInfo이어야하며 getInfo이 서비스 방법으로 지정됩니다. 공장을 사용 Live demo (click).

app.service('myService', function() { 
    // "this" is the service 
    this.foo = function() { 
    console.log('foo from myService1'); 
    }; 
}); 

:

app.factory('myService2', function() { 
    var myService2 = { 
    foo: function() { 
     console.log('foo from myService2'); 
    } 
    }; 

    //what you return from a factory is the service 
    return myService2; 
}); 
+1

정말 고마워

app.service('myService', ['$http', '$q', function($http, $q){ this.getInfo = function(){ return $http({ method: 'GET', url: 'X' }); }; }]); 

다음은 두 개의 일반적인 각도로 서비스를 만드는 예입니다. 당신의 대답이 나를 도왔습니다. –