SystemJs And ES6 Imports For Angular Services - angularjs

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.

Related

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

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);
});
}
}

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)

Angular 1.X Typescript Controller Undefined when using SystemJS

I am using TypeScript with AngularJS 1.5.x and in my tsconfig it all gets compiled down into SystemJS code. Now the issue I am having is only in controller classes that have an import at the top (see example below). If I take these imports out everything works just fine and the controller is found, but if I put them in, the controller is wrapped in a System.register block and it is not found when I go to my view.
I'm a beginner with SystemJS so I'm hoping I am just doing something really dumb, but it has been driving me nuts as to why when I have the imports it does not work.
import { testService} from '../services/test.service';
import { testClass} from '../models/testClass';
namespace app.controllers {
export class testController{
private testService: any;
constructor(public $http: angular.IHttpService) {
}
getData(): any {
}
}
angular.module('app')
.controller('testController', testController);
}

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.

TypeScript Angular - Unknown provider by static $inject ['customServiceName']

In this the repo
In the controller, I'm trying to inject the UserService:
class UserDetailController implements IUserDetailScope {
static $inject = ['app.core.services.UserService']; // static injection
constructor(userService: app.core.services.IUserService) {
But it fails on the browser' console with:
Unknown provider: app.core.services.UserServiceProvider <-
app.core.services.UserService <- UserDetailController
Could you say why?
Try upper casing the "U" in UserService in the constructor. When angular goes to inject, it just does a match on the name of the service, and it matches case.
EDIT
Just realized you're using $inject, I'm leaving the first response up in case some others find it.
You didn't show us the code that registers the service, but that's the next culprit, usually. I'd guess you're registering it as 'UserService', not 'app.core.services.UserService', or else you're doing an App.controller() instead of App.service() registration. Those are the other two major culprits that come to mind.
you are writing the whole namespace to inject a service but there is neat way in which i do
module portal {
var app =angular.module('fooModule',[]);
app.service(services);
app.controller(controllers);
}
module portal.services {
//all your services will go under this namespace
export class fooService{
//service body here
}
}
module portal.controller{
export class UserDetailController implements IUserDetailScope {
static $inject = ['UserService'];
constructor(userService: potal.services.IUserService) {
}
}

Resources