Inject angularjs service into Angular

有些话、适合烂在心里 提交于 2019-12-21 08:49:04

问题


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

  1. Create a module that contains the service you want to inject.
  2. Call UpgradeAdapter's upgradeNg1Provider method.

So, I did the following

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

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 EXCEPTION: No provider for $log!

Also, I tried to bootstrap using upgradeAdapter:

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

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
});

回答1:


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']
    }
  ]
})

and then in place of injection:

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


来源:https://stackoverflow.com/questions/38743423/inject-angularjs-service-into-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!