将angularjs服务注入Angular [英] Inject angularjs service into Angular

查看:130
本文介绍了将angularjs服务注入Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 $ log 服务用于角度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');

然后我创建一个角度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:


ORIGINAL例外:$ log没有提供者!

ORIGINAL EXCEPTION: No provider for $log!

另外,我尝试 bootstrap 使用 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 $状态注入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('...');
  }
}

这篇关于将angularjs服务注入Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆