How do I inject an AngularJS service in an Angular 5 component? - angularjs

I'm migrating an AngularJS project to Angular 5 using ngUpgrade but I'm running into a problem when trying to inject an AngularJS service in one of my new components.
I followed Angular's upgrade guide and created a serviceProvider that uses the $injector (see code below) but I keep getting this error:
core.js:1449 ERROR Error: Uncaught (in promise): Error: Trying to get the AngularJS injector before it being set.
I suspect I need to use forwardRef somewhere to fix this, but I'm unable to find out how and where (and why).
Following the example of the upgrade guide I created a serviceProvider as follows:
ajs-upgraded-providers.ts:
// The AngularJS service I want to use
import { AuthenticationService } from '../ajs/services/authentication.service';
export function authenticationServiceFactory($injector) {
return $injector.get('authentication');
}
export const authenticationServiceProvider = {
provide: AuthenticationService,
useFactory: authenticationServiceFactory,
deps: ['$injector']
};
Then I provide that to the app's NgModule:
app.module.ts:
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
UpgradeModule,
],
providers: [
authenticationServiceProvider,
],
bootstrap: [
AppComponent,
],
})
export class AppModule {
}
I bootstrap that module using ngUpgrade:
main.ts
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { UpgradeModule } from '#angular/upgrade/static';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
// Import our AngularJS module
import '../ajs/app';
platformBrowserDynamic()
.bootstrapModule(AppModule)
.then(platformRef => {
// Use the upgrade module to bootstrap the hybrid
const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document.documentElement, ['myAngularJSApp']);
});
If I understand correctly, this should allow me to directly inject the AngularJS service into my component like so:
login.component.ts
import { Component } from '#angular/core';
import { AuthenticationService } from '../ajs/services/authentication.service';
#Component({
selector: 'my-login-page',
templateUrl: './login-page.component.html'
})
export class LoginPageComponent {
constructor(private authenticationService: AuthenticationService) {
console.log('authentication', authenticationService);
}
}
Can I do anything to simplify this even more? I tried to follow the upgrade guide as closely as possible, so why doesn't this work?

You need to add
providers: [AuthenticationService]
in Component declaration, like this:
import { Component } from '#angular/core';
import { AuthenticationService } from '../ajs/services/authentication.service';
#Component({
selector: 'my-login-page',
templateUrl: './login-page.component.html',
providers: [AuthenticationService]
})
export class LoginPageComponent {
constructor(private authenticationService: AuthenticationService) {
console.log('authentication', authenticationService);
}
}

Related

Using downgradeModule to create an Angular hybrid app

I want to upgrade my Angular JS application to use Angular (2+), and for this I want to use the downgradedModule:
app.module.js (Angular JS module)
import angular from 'angular';
import { environment } from '../environment'
import { downgradeModule } from '#angular/upgrade/static';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
const bootstrapFn = (extraProviders) => {
const platformRef = platformBrowserDynamic(extraProviders);
return platformRef.bootstrapModule(AppModule);
};
const downgradedModule = downgradeModule(bootstrapFn);
(function() {
'use strict';
angular
.module('app', [
/* my other Angular JS modules */
downgradedModule
])
..........
app.module.ts (Angular module)
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { UpgradeModule, setAngularLib } from '#angular/upgrade/static';
import { AppRoutingModule } from './app-routing.module';
import angular from 'angular';
import { MyComponent} from './example-components/my-component.component';
setAngularLib(angular);
#NgModule({
imports: [
BrowserModule,
UpgradeModule,
AppRoutingModule
],
declarations: [
MyComponent
],
entryComponents: [
MyComponent
]
})
export class AppModule {
constructor(private upgrade: UpgradeModule) { }
ngDoBootstrap() {}
}
When I run npm start, it says that angular is not defined and points to the angular.module('app',... line from the app.module.js file. If I go to the only page which contains Angular JS and also Angular components, I don't get any error, but the page is not displaying anything.
If I try to use UpgradeModule into the app.module.ts file like this:
ngDoBootstrap() {
this.upgrade.bootstrap(document.documentElement, ['app'], {
strictDi: false
});
}
The application is working but I get an error into the browser's console:
Error: [$rootScope:inprog] $digest already in progress. I understand that this can be avoided if I use downgradedModule which doesn't work for now as I explained.
Do I have to do something else to bootstrap the application, or what is the problem? Thanks!

How do you get access to the instance of a downgrade component in the view? [duplicate]

What I'm trying to do is to make Angular 2 simple component run inside angular 1 application. I was going through this official guide.
I've faced some issue with injection:
Unknown provider: $$angularInjectorProvider <- $$angularInjector
The stack trace is making no sense, but is obvious that error is raised somewhere deep in the angular itself :)
The structure of my current app looks like this:
ng1.module.ts (entry point):
'use strict';
import { downgradeComponent } from '#angular/upgrade/static';
const angular = require('./lib/angular-wrapper');
const app = angular.module('application', []);
import { AppComponent } from './components/app/app.component.ts';
import { Ng2Module } from './ng2.module.ts';
app.directive(
'app',
downgradeComponent({component: AppComponent}) as angular.IDirectiveFactory
);
angular.bootstrap(document.body, ['application']);
ng2.module.ts:
import 'reflect-metadata';
import '#angular/core';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { UpgradeModule } from '#angular/upgrade/static';
import { AppComponent } from './components/app/app.component.ts';
#NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
entryComponents: [ AppComponent ]
})
export class Ng2Module {
ngDoBootstrap() {}
}
And app.component.ts:
import 'reflect-metadata';
import { Component } from '#angular/core';
#Component({
selector: 'app',
template: "<h1>HELLO WORLD!</h1>"
})
export class AppComponent {}
Asking for any idea on: what can cause the described above error?
This is caused by the UpgradeModule downgraded service that you are using here:
import { UpgradeModule } from '#angular/upgrade/static';
You are using it because you want the UpgradeModule to downgrade an Angular 2 component to angular JS.
If you dig into the code of the UpgradeModule you can find that this module defines a new angular module named $$UpgradeModule.
This module registers a value provider named $$angularInjector (the one in the error above) - this $$angularInjector thing is responsible for injecting Angular modules into angular JS.
The solution is to import the module in the imports statement so that angular JS will have access to its services.
You forgot to import the UpgradeModule. Here is the answer from the official documentation:
#NgModule({
declarations: [Ng2HeroesComponent, Ng1HeroComponentWrapper],
providers: [
HeroesService,
// Register an Angular provider whose value is the "upgraded" AngularJS service
{provide: 'titleCase', useFactory: (i: any) => i.get('titleCase'), deps: ['$injector']}
],
// All components that are to be "downgraded" must be declared as `entryComponents`
entryComponents: [Ng2HeroesComponent],
// We must import `UpgradeModule` to get access to the AngularJS core services
imports: [BrowserModule, UpgradeModule]
})
class Ng2AppModule {
ngDoBootstrap() { /* this is a placeholder to stop the boostrapper from complaining */
}
}
so first you need to change your code to:
ng2.module.ts:
import 'reflect-metadata';
import '#angular/core';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { UpgradeModule } from '#angular/upgrade/static';
import { AppComponent } from './components/app/app.component.ts';
#NgModule({
imports: [ BrowserModule, UpgradeModule ],
declarations: [ AppComponent ],
entryComponents: [ AppComponent ]
})
export class Ng2Module {
ngDoBootstrap() {}
}
Also in order to downgrade your component from ng2 to angular 1
You must create an AngularJS directive that will make this Angular component available inside AngularJS templates:
ng1AppModule.directive('Ng2Module', downgradeComponent({component: AppComponent}));
function downgradeComponent(info: { component: Type< This parameter is no longer used */ selectors?: string[]; }): any;
There is a very helpful post which explains in details how to create a hybrid angular application, and also the scenario when you have a v4 component and you want to use it in the v1 template.

Error in dependency injection when Angular component is downgraded to angularjs

I am in the process of upgrading angularjs app to angular 5 as outlined in this guide
I have the hybrid app bootstrapped from angular code, that went well. As a next step I created an angular5 component which depends on an angular5 service. I have downgraded the component and declared as directive in angularjs. The problem I see is the service doesn't get injected into the component. If I remove the service dependency from the component it works fine.
Here is my code and the error
Component
#Component({
selector: 'test-detail',
template: `
<h2>Windstorm details! {{test}}</h2>
<div><label>id: </label>1</div>
`
})
export class TestComponent {
private test:string;
constructor( private testService:TestService){
}
ngOnInit(){
this.test = this.testService.test();
}
}
Service:
import { Injectable } from '#angular/core';
#Injectable()
export class TestService{
test(){
return "hello";
}
}
NG5 Module
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { UpgradeModule } from '#angular/upgrade/static';
import {TestComponent} from '../ng5/directives/test.directive';
import {TestService} from '../ng5/services/test.service';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
imports: [
BrowserModule,
UpgradeModule,
HttpClientModule
],
declarations:[
TestComponent
] ,
entryComponents: [
TestComponent
],
providers:[
TestService
]
})
export class AppModule {
constructor(private upgrade: UpgradeModule) {
}
ngDoBootstrap() {
this.upgrade.bootstrap(document.documentElement, ['MyApp']);
}
}
AngularJS Module:
angular.module("MyApp").directive('testDetail', downgradeComponent({ component: TestComponent }) as angular.IDirectiveFactory);
The error I get when launching the page is
uncaught Error: Can't resolve all parameters for TestComponent: (?).
at syntaxError (compiler.js:485)
at CompileMetadataResolver.webpackJsonp.529.CompileMetadataResolver._getDependenciesMetadata (compiler.js:15699)
at CompileMetadataResolver.webpackJsonp.529.CompileMetadataResolver._getTypeMetadata (compiler.js:15534)
at CompileMetadataResolver.webpackJsonp.529.CompileMetadataResolver.getNonNormalizedDirectiveMetadata (compiler.js:15019)
at CompileMetadataResolver.webpackJsonp.529.CompileMetadataResolver._getEntryComponentMetadata (compiler.js:15847)
at compiler.js:15317
at Array.map (<anonymous>)
at CompileMetadataResolver.webpackJsonp.529.CompileMetadataResolver.getNgModuleMetadata (compiler.js:15317)
at JitCompiler.webpackJsonp.529.JitCompiler._loadModules (compiler.js:34404)
at JitCompiler.webpackJsonp.529.JitCompiler._compileModuleAndComponents (compiler.js:34365)
I am answering my own question. Declaring service the following way resolved the issue
providers:[
{ provide: 'TestService', useClass: TestService }
]

Can't resolve all parameters for Auth: (?) error, ionic2 AngularJS

i wanted to provide authonification to my ionic2 app, so i followed the official documentation and applied it to a brand new ionic2 app ionic start my_app blank
once i serve my app, this error fires :
Error: Can't resolve all parameters for Auth: (?).
at syntaxError (http://localhost:8100/build/main.js:107898:34)
at CompileMetadataResolver._getDependenciesMetadata (http://localhost:8100/build/main.js:121235:35)
at CompileMetadataResolver._getTypeMetadata (http://localhost:8100/build/main.js:121103:26)
at CompileMetadataResolver._getInjectableMetadata (http://localhost:8100/build/main.js:121089:21)
at CompileMetadataResolver.getProviderMetadata (http://localhost:8100/build/main.js:121379:40)
at http://localhost:8100/build/main.js:121308:49
at Array.forEach (<anonymous>)
at CompileMetadataResolver._getProvidersMetadata (http://localhost:8100/build/main.js:121269:19)
at CompileMetadataResolver.getNgModuleMetadata (http://localhost:8100/build/main.js:120924:50)
at JitCompiler._loadModules (http://localhost:8100/build/main.js:131988:66)
i've injected Auth with providers in app.moodule.ts as you can
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { MyApp } from './app.component';
import { Auth } from '#ionic/cloud-angular';
#NgModule({
declarations: [
MyApp,
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
],
providers: [
StatusBar,
SplashScreen,
Auth,
{provide: ErrorHandler, useClass: IonicErrorHandler }
]
})
export class AppModule {}
according to my researches, this error comes from:
Having forgot to decorate the Auth class with #Injectable() or #Inject(Auth)
i have tried doing so by injecting :
#IonicPage()
#Component({
selector: 'page-home',
templateUrl: 'home.html',
})
#Injectable()
export class HomePage {........}
OR
export class HomePage {
constructor(#Inject(Auth) public auth: Auth) {
}
.......
}
But this shows the same error though.
Having a dependency in the Auth constructor that i haven't provided in app.module.ts
as you can see, i've handled this case in my code.
A circular dependency.
which i really think is the issue here, honestly i got a clue how to check this out since i still a beginner.
Hope someone can help

Angular2 Component in Angular1 App

What I'm trying to do is to make Angular 2 simple component run inside angular 1 application. I was going through this official guide.
I've faced some issue with injection:
Unknown provider: $$angularInjectorProvider <- $$angularInjector
The stack trace is making no sense, but is obvious that error is raised somewhere deep in the angular itself :)
The structure of my current app looks like this:
ng1.module.ts (entry point):
'use strict';
import { downgradeComponent } from '#angular/upgrade/static';
const angular = require('./lib/angular-wrapper');
const app = angular.module('application', []);
import { AppComponent } from './components/app/app.component.ts';
import { Ng2Module } from './ng2.module.ts';
app.directive(
'app',
downgradeComponent({component: AppComponent}) as angular.IDirectiveFactory
);
angular.bootstrap(document.body, ['application']);
ng2.module.ts:
import 'reflect-metadata';
import '#angular/core';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { UpgradeModule } from '#angular/upgrade/static';
import { AppComponent } from './components/app/app.component.ts';
#NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
entryComponents: [ AppComponent ]
})
export class Ng2Module {
ngDoBootstrap() {}
}
And app.component.ts:
import 'reflect-metadata';
import { Component } from '#angular/core';
#Component({
selector: 'app',
template: "<h1>HELLO WORLD!</h1>"
})
export class AppComponent {}
Asking for any idea on: what can cause the described above error?
This is caused by the UpgradeModule downgraded service that you are using here:
import { UpgradeModule } from '#angular/upgrade/static';
You are using it because you want the UpgradeModule to downgrade an Angular 2 component to angular JS.
If you dig into the code of the UpgradeModule you can find that this module defines a new angular module named $$UpgradeModule.
This module registers a value provider named $$angularInjector (the one in the error above) - this $$angularInjector thing is responsible for injecting Angular modules into angular JS.
The solution is to import the module in the imports statement so that angular JS will have access to its services.
You forgot to import the UpgradeModule. Here is the answer from the official documentation:
#NgModule({
declarations: [Ng2HeroesComponent, Ng1HeroComponentWrapper],
providers: [
HeroesService,
// Register an Angular provider whose value is the "upgraded" AngularJS service
{provide: 'titleCase', useFactory: (i: any) => i.get('titleCase'), deps: ['$injector']}
],
// All components that are to be "downgraded" must be declared as `entryComponents`
entryComponents: [Ng2HeroesComponent],
// We must import `UpgradeModule` to get access to the AngularJS core services
imports: [BrowserModule, UpgradeModule]
})
class Ng2AppModule {
ngDoBootstrap() { /* this is a placeholder to stop the boostrapper from complaining */
}
}
so first you need to change your code to:
ng2.module.ts:
import 'reflect-metadata';
import '#angular/core';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { UpgradeModule } from '#angular/upgrade/static';
import { AppComponent } from './components/app/app.component.ts';
#NgModule({
imports: [ BrowserModule, UpgradeModule ],
declarations: [ AppComponent ],
entryComponents: [ AppComponent ]
})
export class Ng2Module {
ngDoBootstrap() {}
}
Also in order to downgrade your component from ng2 to angular 1
You must create an AngularJS directive that will make this Angular component available inside AngularJS templates:
ng1AppModule.directive('Ng2Module', downgradeComponent({component: AppComponent}));
function downgradeComponent(info: { component: Type< This parameter is no longer used */ selectors?: string[]; }): any;
There is a very helpful post which explains in details how to create a hybrid angular application, and also the scenario when you have a v4 component and you want to use it in the v1 template.

Resources