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.
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");
}
}
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
$locationor$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
HeroesServicein 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.tsfile 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
heroesServiceFactoryfunction so that Ahead-of-Time compilation can pick it up.— Angular Developer Guide - Upgrading (Making AngularJS Dependencies Injectable)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With