17

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
});
3
  • Seems like a similar question. Check this out, you may want to use bindings or providers stackoverflow.com/a/32298993/1403009 Commented Aug 3, 2016 at 12:30
  • @NaveenAechan That answer does not appear to be helpful, as it assumes you have access to the Angular 2 provider object. UpgradeAdapter.upgradeNg1Provider does not return anything. Commented Sep 27, 2016 at 21:21
  • 1
    Just refer to 'Angular' if you are referring to Angular 2+ Commented Jul 25, 2017 at 4:28

2 Answers 2

23

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('...');
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

$injector is undefined
This worked for me using an AngularJS 1.4.7 service with Angular 7.2.0
2

The answer from @Liovareg works much better than the official documentation. My Angular (1.5.x) service was in a JS file and it was the @Inject that I was missing in Angular 13 (and is different than the official docs).

Angular JS:

(function () {
    angular
        .module('common')
        .service('appContext', appContext);

    appContext.$inject = ['$cookies', 'moment', '$location', 'userCacheFactory', 'urlHrefCacheFactory', 'lock'];

    function appContext($cookies, moment, $location, userCacheFactory, urlHrefCacheFactory, lock) {
      ...
      function renewSession() {
        ...
      }
      ...
      return {
        renewSession: renewSession,
        ...
      };
    };
})();

ajs-upgraded-providers.ts (resides at the same level as app.module.ts):

// @ts-ignore
import { appContext } from '../../../app/common/appContext';

export function appContextServiceFactory(injector: any) { // eslint-disable-line @typescript-eslint/no-explicit-any
  return injector.get('appContext');
}

export const ajsAppContextServiceProvider: any = { // eslint-disable-line @typescript-eslint/no-explicit-any
  deps: ['$injector'],
  provide: 'appContext',
  useFactory: appContextServiceFactory
};

app.module.ts:

import { ajsAppContextServiceProvider } from './ajs-upgraded-providers';
...
@NgModule({
  ...
  providers: [
    ...,
    ajsAppContextServiceProvider
  ]
})
...

Angular 13 (foo.service.ts):

...
@Injectable({
  providedIn: 'root'
})
export class SessionTimeoutService {
  ...
  public constructor(
    @Inject('appContext') private ajsAppContextService: any, // eslint-disable-line @typescript-eslint/no-explicit-any
    ...
  )
  ...
  public someMethod(): void {
    this.ajsAppContextService.renewSession();
  }
  ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.