Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migration to Angular2: How to use injected AngularJS dependencies

How Am I supposed to use an AngularJS dependency during migration to Angular2 outside the constructor? I am using upgrade module and service is not yet upgraded.

like image 777
Olezt Avatar asked Jan 23 '26 05:01

Olezt


2 Answers

So the answer was partially Making AngularJS Dependencies Injectable to Angular but it was not demonstrated how to make it available outside the constructor.

Here is an example for the $log angularJS service.

Create ajs-upgraded-providers.ts where we declare the provider:

/**
 * $log upgraded provider
 */
export abstract class Log {
  [key: string]: any;
}

export function logFactory(i: any) {
  return i.get('$log');
}

export const logProvider = {
  provide: Log,
  useFactory: logFactory,
  deps: ['$injector']
};

Import to app.module.ts the declared provider:

import { logProvider } from './ajs-upgraded-providers';

@NgModule({
  imports: [
    //imports
  ],
  providers: [
    //Providers & Services

    //Upgraded angularJS providers
    logProvider
  ]
})

example.service.ts How to use the angularJS service while migration takes place:

import { Log } from '../ajs-upgraded-providers'; //edit path accordingly

@Injectable()
export class ExampleService {

  constructor(private $log: Log) {}

  exampleFunction() {
     this.$log.info("Info to be logged");
  }

}
like image 200
Olezt Avatar answered Jan 24 '26 22:01

Olezt


Making AngularJS Dependencies Injectable to Angular

When running a hybrid app, we may bump into situations where we need to have some AngularJS dependencies to be injected to Angular code. This may be because we have some business logic still in AngularJS services, or because we need some of AngularJS's built-in services like $location or $timeout.

In these situations, it is possible to upgrade an AngularJS provider to Angular. This makes it possible to then inject it somewhere in Angular code. For example, we might have a service called HeroesService in AngularJS:

import { Hero } from '../hero';
export class HeroesService {
  get() {
    return [
      new Hero(1, 'Windstorm'),
      new Hero(2, 'Spiderman')
    ];
  }
}

We can upgrade the service using a Angular Factory provider that requests the service from the AngularJS $injector.

We recommend declaring the Factory Provider in a separate ajs-upgraded-providers.ts file so that they are all together, making it easier to reference them, create new ones and delete them once the upgrade is over.

It's also recommended to export the heroesServiceFactory function so that Ahead-of-Time compilation can pick it up.

— Angular Developer Guide - Upgrading (Making AngularJS Dependencies Injectable)

like image 28
georgeawg Avatar answered Jan 24 '26 22:01

georgeawg