将 angularjs 服务注入 Angular

我正在尝试将 $log 服务用于 Angular 2,根据我阅读的内容,您需要以下步骤:

I'm trying to use $log service into an angular 2, According to what I read you need the following steps:

  1. 创建一个包含您要注入的服务的模块.
  2. 调用 UpgradeAdapter 的 upgradeNg1Provider 方法.

所以,我做了以下

  var initInjector = angular.injector(['ng']);
  var $log = initInjector.get('$log');
  angular.module('Services1', [])
    .service('$log', [$log]);
  upgradeAdapter.upgradeNg1Provider('$log');

然后我创建一个 angular 2 组件,如下所示

Then I create an angular 2 component as the following

    @Component({   selector: "ion-app",   template:"<p>Test</p>" })
    @Injectable()
    export class HelloIonicPage {
      message: string;
      constructor( @Inject('$log') $log) {
        this.message = "Hi";
      }
    }

但是当我运行应用程序时,它给了我以下错误:

But when I run the application it gives me the following error:

原始异常:$log 没有提供程序!

ORIGINAL EXCEPTION: No provider for $log!

另外,我尝试使用 upgradeAdapter bootstrap:

Also, I tried to bootstrap using upgradeAdapter:

  upgradeAdapter.bootstrap(document.documentElement, ['Services1'])

但这也不起作用.请注意,我使用的是 Ionic 2 框架,上面的代码是写在里面的

But that didn't work also. Please note that I'm using Ionic 2 framework and the above code is written inside

    this.platform.ready().then(() => { 
            //The code is going here
});

推荐答案

您需要将服务注册为提供者.这是我将 angular1 $state 注入到 angular 2 应用程序的方法:

You need to register service as provider. Here is how I inject angular1 $state to angular 2 application:

@NgModule({
  providers: [
    {
       provide: '$state', 
       useFactory: ($injector: any) => $injector.get('$state'), 
       deps: ['$injector']
    }
  ]
})

然后代替注入:

@Injectable()
export class RestService {
  constructor(@Inject('$state') $state: any) {
    $state.go('...');
  }
}

相关文章