将升级的服务注入组件

时间:2016-01-15 07:53:06

标签: javascript angularjs angular

我在我的angular 1应用程序中使用了一个名为Example的服务。它有角度1依赖,$resource, $http, $q,我想在我的角度2服务中使用它。

但以下是我尝试实施升级的方法。

var ExampleService = require('./service.js');

angular.module('angular-legacy',[]).service('example', ExampleService);
upgradeAdapter.upgradeNg1Provider('example');

var AppComponent =
  ng.core.Component({
    selector: 'app',
    providers: [ExampleService]
  })
  .View({
    template: ' <div>Hello </div> ',
  })
  .Class({
    constructor: [ExampleService, function (service) {
      console.log(service);
    }]
  });

我在这些方面遇到错误。

cannot resolve all parameters for 'ExampleService'(?, ?, ?, ?, ?).

有没有办法可以注入ExampleService的升级版本?

1 个答案:

答案 0 :(得分:0)

经过一番挣扎,我想出了这个。我把所有内容打包在一个小例子中,以便让将来遇到这种情况的人轻松。

https://github.com/danielrasmuson/Angular2-Use-Angular1Service-ES5

这是它的内容。

var core = require('angular2/core');
var bootstrap = require('angular2/platform/browser').bootstrap;
var UpgradeAdapter = require('angular2/upgrade').UpgradeAdapter;
var ng = {
    core: core
}

var AppComponent = 
    ng.core.Component({
        selector: 'app'
    })
    .View({
        template: '<h1>working</h1>'
    })
    .Class({
        constructor: function(pinsService){
            pinsService.working();
        }
    });

AppComponent.parameters = [new ng.core.Inject('PinsService')];

angular.module('interestApp', [])
.service('PinsService', function($http, $q) {
    this.working = function(){
        alert('servicce working');
    }
});

var upgradeAdapter = new UpgradeAdapter();
angular.module('interestApp')
  .directive('app', upgradeAdapter.downgradeNg2Component(AppComponent))
upgradeAdapter.upgradeNg1Provider('PinsService');

upgradeAdapter.bootstrap(document.body, ['interestApp']);