将 angularjs 服务注入 Angular

Inject angularjs service into Angular(将 angularjs 服务注入 Angular)
本文介绍了将 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('...');
  }
}

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I can get a text of all the cells of the table using testcafe(如何使用 testcafe 获取表格中所有单元格的文本)
node_modules is not recognized as an internal or external command(node_modules 未被识别为内部或外部命令)
How can I create conditional test cases using Protractor?(如何使用 Protractor 创建条件测试用例?)
PhantomJS and clicking a form button(PhantomJS 并单击表单按钮)
Clicking #39;OK#39; on alert or confirm dialog through jquery/javascript?(在警报上单击“确定或通过 jquery/javascript 确认对话框?)
QunitJS-Tests don#39;t start: PhantomJS timed out, possibly due to a missing QUnit start() call(QunitJS-Tests 不启动:PhantomJS 超时,可能是由于缺少 QUnit start() 调用)