2014-02-13 46 views
0

我想连接一个简单的数据服务来从服务器检索http调用数据。我正在使用TypeScript来编写代码。出于某种原因,我无法获得服务来查看其依赖关系。 这里是服务它是由打字稿 由angularjs工厂创建的数据服务不依赖

var app = angular.module('app',[]); 
app.constant('baseUrl', 'http://localhost:63342'); 

//This follows the pattern created by Typescript 
var myService = function(){ 
    function myService($http, baseUrl){ 
     this.$http = $http; 
     this.baseUrl = baseUrl; 
     this.http = typeof this.$http; 
     this.url = typeof this.baseUrl; 
    } 
    myService.$inject = ['$http', 'baseUrl']; 
    return myService 
} 

app.factory('myService', [ 
    '$http', 'baseUrl', 
    myService 
]); 

app.controller('myCtrl', 
     ['$scope', 'myService', 
      function($scope, myService){ 
       $scope.httpType = myService.http; 
       $scope.urlType = myService.url}] 
); 

产生的方式,当我运行的代码在本地p标签得到了NG-绑定属性在他们设置。但是,当然,他们没有任何东西。当我分配$ scope分配时,myService是可用的,它有$ inject变量,但没有其他4个变量。 Typescript和angular的可用示例非常薄。必须有一些基本的东西我做错了。

Here is a fiddle with the code.我不知道为什么小提琴没有跨越范围变量。

回答

0

我能够使它遵循模块模式来公开服务的属性,并使用内联符号声明服务。看看这里的运动员:http://plnkr.co/edit/tVajIshcCegIwywGWL9Y?p=preview。粘贴下面的脚本代码:

var app = angular.module('app',[]); 
app.constant('baseUrl', 'http://developer.echonest.com/api/v4/artist/news?api_key=FILDTEOIK2HBORODV&id=7digital-US:artist:304&format=json'); 


app.factory('myService', ['$http', 'baseUrl', function($http,baseUrl){ 
     var http = typeof $http; 
     var url = typeof baseUrl; 
     return { 
      http: http, 
      url : url 
     }; 
    }]); 

app.controller('myCtrl', 
       ['$scope', 'myService', 
       function($scope, myService){ 
       $scope.httpType = myService.http; 
       $scope.urlType = myService.url; 
       }]    
      ); 
+0

也忽略使用还有其他网址并重新替换你自己的baseurl。 – ossek

+0

我现在已经创建了3个示例,从头开始计算出哪里出错,其中两个服务现在正在获取其依赖关系,但控制器没有获得对服务的依赖,所以我现在可能会发布代码,看看我回来了。 – pthalacker

1

的问题是:

var myService = function(){ 
    function myService($http, baseUrl){ 
     this.$http = $http; 
     this.baseUrl = baseUrl; 
     this.http = typeof this.$http; 
     this.url = typeof this.baseUrl; 
    } 
    myService.$inject = ['$http', 'baseUrl']; 
    return myService 
} 

app.factory('myService', [ 
    '$http', 'baseUrl', 
    myService 
]); 

角将调用myService带参数的$http,baseUrlmyService不接受。所以,你需要做的:

var myService = function($http, baseUrl){ 
      this.$http = $http; 
      this.baseUrl = baseUrl; 
      this.http = typeof this.$http; 
      this.url = typeof this.baseUrl; 
} 
myService.$inject = ['$http', 'baseUrl']; 

另外,如果你想使用打字稿类使用相同的模式,我建议为控制器:http://www.youtube.com/watch?v=WdtVn_8K17E&hd=1和使用service代替factory

+0

myService接受内部函数中的参数,而不是外部参数。这是TypeScript生成的代码。它与视频中的MainController相同。我没有在视频中看到你在应用程序中注册控制器。几乎我见过的创建后端数据服务的每个示例都使用工厂来创建它,因此我一直在关注这些示例。 – pthalacker

+0

@pthalacker我创建了一个视频来演示推荐的服务模式:http://www.youtube.com/watch?v=Yis8m3BdnEM&hd=1 + github https://github.com/basarat/video-angularjs-打字稿服务 – basarat