将 angularjs 服务注入 Angular

时间:2023-03-16
本文介绍了将 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:ionic 2 + angular 2:自动滚动到列表/页面/聊天的底部 下一篇:ionic - 如何在 ion-header 中对长字符串进行自动换行

相关文章