How to use 3rd party AngularJS (1.6) module (angular-translate) in Angular (2 or 4) - angularjs

The case
I am in the process of upgrading an AngularJS (i.e. Angular 1.6) application to Angular (i.e. Angular 4.1.3). I chose to do the incremental upgrade so currently both AngularJS and Angular are bootstrapped and running. So far so good, but: One of the AngularJS services that should be rewritten to Angular relies on a well known service $translate which is part of the 3rd party AngularJS (read Angular 1) module pascalprecht.translate. In other words, $translate service is injected to MyService which should become an Angular (read Angular 4) service.
MyService (stripped down) looks like this:
import { Injectable } from '#angular/core';
#Injectable()
export class MyService {
// Here comes the injection (how to do it?).
constructor(private $translate: $translate) {
}
foo() {
// Use the service
this.$translate('HELLO_WORLD');
}
}
It is located within MyModule:
import { NgModule } from '#angular/core';
import { MyService } from './my.service';
#NgModule({
providers: [
MyService
]
})
export class MyModule {
}
The problem
Now, how can I inject $translate into MyService when MyService resides within an Angular module while $translate is part of a 3rd party AngularJS module?
I know how to inject an AngularJS service into an Angular service if the AngularJS service is located within the same module (or at least the module is part of my own solution). It is explained in the official docs. Is there any way to handle a 3rd party service? Do I need to register that service within MyModule's providers?
import { NgModule } from '#angular/core';
import { MyService } from './my.service';
// How this line should look line then?
import { $translate } from 'node_modules/angular-translate/...';
#NgModule({
providers: [
MyService,
$translate
]
})
export class MyModule {
}
Or am I trying to achieve impossible?

Well, after a few hours of struggling I've finally found the solution. Here it is:
Upgrade the 3rd party service
First of all, follow the Angular's official guidelines and upgrade the provider of the 3rd party service - $translate. Like this:
ajs-upgraded-providers.ts
import { InjectionToken } from '#angular/core';
import { downgradeInjectable } from '#angular/upgrade/static';
import 'angular-translate';
// Variable 'i' holds the standard AngularJS injector
export function $translateFactory(i: any) {
return i.get('$translate');
};
// There is no class representing the good old $translate service so we have
// a non-class dependency. Therefore we use an InjectionToken (Angular 4) or
// OpaqueToken (Angular 2).
export let $translate = new InjectionToken('$translate');
// Finally create the upgraded provider
export const $translateProvider = {
provide: $translate,
useFactory: $translateFactory,
deps: ['$injector']
};
One thing to notice, the $translate service might be dependent on other old AngularJS services like (in my case) $translateStaticFilesLoader or $translateMessageFormatInterpolation. If this is also your case, be sure to extend the code above and make upgraded providers for those services as well (keep them in the same file).
Make sure the import statement works
The angular-translate is installed as a node module so the statement
import 'angular-translate';
works just fine if your tsconfig.json is set up to use moduleResolution: "node".
Then, of course, you need to ensure that the import statement will work even after the code is transpiled from TypeScript to ES5 (or whichever target you use) and picked up by a module loader (SystemJS in my case).
Notice that we imported the angular-translate script without getting anything from it, just to cause side effects. Basically, the import ensures that the script containing the desired service $translate is simply executed and registers $translate service for the AngularJS $injector.
Register the upgraded provider in Angular module
Now ensure that the new upgraded provider of $translate service is registered among other providers of MyModule.
my.module.ts
import { NgModule } from '#angular/core';
import { MyService } from './my.service';
import { $translateProvider } from './ajs-upgraded-providers';
#NgModule({
providers: [
MyService,
$translateProvider
]
})
export class MyModule {
}
Use it
Finally, use the $translate service in MyService.
my.service.ts
import { Injectable, Inject } from '#angular/core';
import { $translate } from './ajs-upgraded-providers';
#Injectable()
export class MyService {
// Notice the usage of InjectionToken
constructor(#Inject($translate) private $translate: any) {
}
foo() {
this.$translate('hello.world').then((translation: string) => {
console.log(translation);
});
}
}

Related

How to inject AngularJS dependencies while calling from Angular module

I am trying to host a simple hybrid application (AngularJS + Angular 7). I was able to set the basic and bootstrap both the modules based on the guidelines. I was able to establish the communication from AngularJS to Angular.
I followed the guidelines for injecting AngularJS service in the Angular module ( https://angular.io/guide/upgrade ). However, I see there are few issues that I am stuck with which could be a basic set up which I am trying to understand.
Here is the real issue, When I try to call the AngularJS service from Angular, it fails during the run time stating the dependency injected in AngularJS service is undefined. For ex: $http is not defined.
My question is, do I need to inject this dependency through a provider in the Angular module, I have a provider which injects the service itself to the Angular module. Any help with the guidelines or standards would be helpful.
Here is the format of my AngularJS service. At present, I am modifying this to class and trying to invoke from Angular
function GetUsers( $http, OtherDependency) {
return {
getUsers: getUsers
}
function getUsers(userID, key, phrase) {
//$http is used inside this method
}
In angular, I am injecting this service through a provider and trying to use this service by instantiating through its constructor
Since your stackbliz demo is not runnable, from my project, I just create a Angular SharedModule and inject angularjs services to provider like below:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
export function getToastrService($injector: any) {
return $injector.get('toastr');
}
export function getLoadingService($injector: any) {
return $injector.get('loadingService');
}
#NgModule({
imports: [
CommonModule
],
exports: [
NgxComponentsModule
],
providers: [
{ provide: 'toastr', deps: ['$injector'], useFactory: getToastrService },
{ provide: 'loadingService', deps: ['$injector'], useFactory: getLoadingService }
]
})
export class NgxSharedModule { }
And then in my Angular business module, import SharedModule, and then only need to use DI in constructor:
constructor(#Inject('toastr') public toastr: any,
private notifyService: NotifyService) { }
Hope it will work for you.

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.
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 $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)

What is the equivalent of a factory in Angular2?

So I am used to using factories & services in Angular.
I am reading through the Angular2 docs and I don't see any equivalent of a factory. What is the equivalent for Angular2?
Factories, services, constants and values are all gone in Angular2. Angular2 is radically and fundamentally different from the classic Angular. In Angular2, the core concepts are
components
dependency injection
binding
The idea of services, factories, providers and constants has been criticized in Angular 1. It was difficult to choose between one. Removing them simplifies things a bit.
In the original Angular, you would define a service like so
app.service('BookService', ['$http', '$q', BookService]);
function BookService($http, $q){
var self = this;
var cachedBooks;
self.getBooks = function(){
if (cachedBooks) {
return $q.when(cachedBooks);
}
return $http.get('/books').then(function(response){
cachedBooks = response.data.books;
return cachedBooks;
})
}
}
Angular2 significantly leverages ES6 syntax to make the code more readable and easier to understand.
One new keyword in ES6 is class, which can be thought of as a service.
ES6 classes are a simple sugar over the prototype-based OO pattern. Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.
Here's how that same code might look in Angular2
import {HttpService, Promise} from '../Angular/Angular2';
export class BookService{
$http, $q, cachedBooks;
constructor($http: HttpService, $q: Promise) {
this.$http = $http;
this.$q = $q
}
getBooks() {
if (this.cachedBooks) {
return this.$q.when(this.cachedBooks);
}
return this.$http.get('/books').then(function(data) {
this.cachedBooks = data.books;
return this.cachedBooks;
})
}
}
#Richard Hamilton's answer is appreciated and in addition to that there are few points to note.
For Factories,Service, and etc, in Angular2 we have service (or shared service). we have to make our service Injectable in order to use it.
NOTE: This code belongs to beta version and not RC.
import {Component, Injectable,Input,Output,EventEmitter} from 'angular2/core'
import {Router} from 'angular2/router';
import {Http} from 'angular2/http';
export interface ImyInterface {
show:boolean;
}
#Injectable() <---------------------------- Very Important
export class sharedService { <----------------- Service Name
showhide:ImyInterface={show:true};
constructor(http:Http;router:Router)
{
this.http=http;
}
change(){
this.showhide.show=!this.showhide.show;
}
}
If I want to use everywhere in my app, then I have to inject this service in bootstrap function like this,
bootstrap(App, [HTTP_PROVIDERS,sharedService <--------Name Injection
ROUTER_PROVIDERS,bind(APP_BASE_HREF).toValue(location.pathname)
]);
This way it creates single instance of your service. If you don't want to go with single instance, what you can do is - you can use Providers:[sharedService] metadata in you #component decorator.
Then, use it in your one of components like this,
export class TheContent {
constructor(private ss: sharedService) { <--------Injection dependency of your newly created service
console.log("content started");
}
showhide() {
this.ss.change(); <----- usage
}
}
Check working example here
I don't know what factories do exactly in Angular1 but in Angular2 there is useFactory:
{
provide: SomeClass,
useFactory: (dep1, dep2) => (x) => new SomeClassImpl(x, dep1, dep2),
deps: [Dep1, Dep2]
}
to provide your own instance construction logic if the default doesn't match your needs.
You can also inject a factory to create new instances yourself:
/* deprecated or removed depending on the Angular version you are using */
provide(SomeClass, {
useFactory: (dep1, dep2) => {
(x) => new SomeClassImpl(x, dep1, dep2),
},
deps: [Dep1, Dep2]
})
constructor(#Inject(SomeClass) someClassFactory: any) {
let newSomeClass = someClassFactory(1);
}
Argument x must have type assignment, otherwise angular doesn't know how to deal with it.
class SomeClassImpl {
constructor(x: number, dep1: Dep1, dep2: Dep2){}
}
If you need a new instance of a service in some component you need to provide it in that component like this:
#Component({
selector: 'hero-list',
templateUrl: './hero-list.component.html',
providers: [ HeroService ]
})
This will generate a new instance of the HereService as a factory does.

SystemJs And ES6 Imports For Angular Services

I've got a pretty serious problem. I'm trying to make steps toward ES6 imports and TypeScript in my Angular 1 application. But with angular injection many ES6 imports go unused. Here is an example:
Service-
export class MyService {
public doStuff() {}
}
Controller-
import {MyService} from './service';
export class MyController {
public constructor(private MyService: MyService) {MyService.doStuff();}
}
Note it does not matter if I rename the import using as.
The problem here is that the compiler doesn't think the MyService import is being used! So the resulting compiled systemjs code does not include it-
System.register('myController', [], function() { ... });
To get around this I could make the methods on MyService static and never inject it using angular. Ex:
import {MyService} from './service';
export class MyController {
public constructor() {MyService.doStuff();}
}
But we don't have the time to do that. We are trying to do this refactor in steps, and while that's the ultimate goal, we don't have time for that at the moment.
How do I force systemjs to include these?
From the TypeScript Handbook
Import a module for side-effects only
Though not recommended practice, some modules set up some global state that can be used by other modules. These modules may not have any exports, or the consumer is not interested in any of their exports. To import these modules, use:
import "./my-module.js";
The correct way to handle this is to register the service with the angular.service before application startup. TypeScript is eliding the import because it is only used in type position, not in value position. This is not specific to "module": "system", but applies to all external module targets.
Here is what I have used successfully in a number of production apps
my-service.ts
export class MyService {
doStuff() {}
}
my-controller.ts
import {MyService} from './service';
export class MyController {
static $inject = ['MyService'];
constructor(private myService: MyService) {
myService.doStuff();
}
}
my-app.ts
import angular from 'angular';
import {MyController} from './my-controller';
import {MyService} from './my-service';
const app = angular.module('app', []);
app.controller({ MyController });
app.service({ MyService });
export function bootstrap(target: Document | Element) {
angular.bootstrap(target, ['app'], { ngStrictDi: true });
}
To explain, the service itself needs to be registered with an angular module in order to be injected in the first place, so the elided import is a non issue since the registration code, shown in my-app.ts, uses MyService in value position when passing it as an argument to angular.service.
A nice pattern is to register all of the services that comprise a certain set of functionality in a single place. The logical place to do this is in the file containing the angular module which will hold the services.
Also note the static $inject = ['MyService']; this ensures your controller code is minification safe while allowing you to co-locate the DI annotation with the constructor that requires it.
I have found this pattern scales very well.

Angular2 upgradeAdapter not working with $rootScope, $state etc

Im trying to upgrade an Angular1 application with the help of Angular2's upgradeAdapter. The app is bootstrapped with the upgradeAdapter and works as expected, at least as long as I don't try to upgrade one of A1's integrated services.
Let's say i have this A1 Service written in typescript:
//A1.ts
// inject decorator that in short does target.$inject = ...injects
#Inject('$rootScope')
class TestService{
constructor($rootScope: angular.IRootScopeService){
//$rootScope.whatever();
}
}
// register the service in application module
globalModule.service('TestService', TestService);
I can inject the TestService the normal A1 way wherever I need to, and it works.
Now for the A2 upgrade i do:
//upgradeAdapter.ts
import {UpgradeAdapter} from 'angular2/upgrade';
const upgradeAdapter = new UpgradeAdapter();
export default upgradeAdapter;
//A2.ts
import upgradeAdapter from './upgradeAdapter'
import { Injectable, Inject} from 'angular2/core'
#Injectable()
export class A2TestService{
constructor(#Inject('$rootScope') _rootScope: angular.IRootScope){
//_rootScope.whatever()
}
}
upgradeAdapter.upgradeNG1Provider('$rootScope');
// tried with additional upgradeAdapter.upgradeNG1Provider('$rootScopeProvider');
upgradeAdapter.addProvider(A2TestService);
// make this service available in A1 World
globalModule.service('A2TestService',upgradeAdapter.downgradeNG2Provider(A2TestService));
Hybrid DI works when upgrading with this formula, as long as I don't use, e.g., $rootScope like above.
Then I am getting
"Error during instantiation of $rootScope! (A2TestService -> $rootScope)
Stacktrace: Type Error: Cannot read property 'get' of null
at provider.push.core_1.provide.useFactory (upgrade.js: 684)
..."
coming from angular2.js (on beta.9)
What are my options here?

Resources