Instantiate Angular JS service using - injector.get() - angularjs

I have an Angular 1.x application. Now that there is a use case where in I have to access the Angular 1.x Services / Factories in ES6 Classes which are not part of or registered with Angular JS. In short I would want to do something like export an Angular Service and import in ES6 class. I know this is not directly possible but will there be a work around ?
So I have a service like
(function () {
angular.module('myApp').service('ServiceOne', function () {
return {
property: value
};
});
})();
and now there is an ES6 class another (service file)...
import angular from 'angular';
// const $injector = angular.injector(['ng', 'myApp']);
// const ServiceOne = $injector.get('ServiceOne');
// const ServiceTwo = $injector.get('ServiceTwo');
class Es6Service {
constructor() {
//this.serviceOne = ServiceOne;
//this.serviceTwo = ServiceTwo;
}
methodOne() {
// code
}
methodTwo() {
// code
}
}
export default Es6Service;
I know that injector.get('serviceName') can get us the service instance, in my case I am getting an error of unknown provider. My assumption is that the angular module reference is missing perhaps here.
If that is the case then how can I get the Module reference here ? or there is some other way to achieve this ?
Thanks

Looks strange but should work:
import angular from 'angular';
let _$injector;
angular.module('myApp').run($injector => _$injector = $injector);
class Es6Service {
methodOne() {
// Cannot call this method until angular initialize
return _$injector.get(...)
}

Related

Angular JS $injector - get dependencies

I need to get the instances of my Services/Factory in my Angular JS application. For that reason I would want to use $injector so as to get instances and not depend on DI. I tried to create a wrapper method over $injector which is a seperate js file so that any other modules can call this helper method and get necessary instances. I know this is not straight forward but still wanted to try.
For this my code looks like
//helper.js file
export default function returnInstances(service) {
const app = angular.module('moduleName');
let instance;
app.run(() => {
injector = angular.injector(['ng', 'moduleName']);
instance = injector.get(service);
});
return instance;
}
// some other file
const instance = returnInstances('serviceName');
As expected this does not work. So I was wondering if anything like this is possible.
const helper = {
init: (injector) => this.injector = injector;
get: (name) => this.injector.get(name);
}
export default helper;
And in file where you bootstrap your module:
app.run((['$injector'], $injector) => helper.init($injector));
angular.bootstrap(...
And then u can use it.

'angular is not defined' in mocha tests

I'm trying to test a controller function which does a very basic task, some snippets below
I import an enum from a custom module I made
import { CurrentUser, Right } from "habenero-identity";
In the controller, I then have the following function
entercanAddModem = () => {
this.user.hasRight(Right.AddModem);
};
When i try to test this with:
#test
canAddModemCallsUserHasRight() {
this.user = { hasRight: sinon.spy() };
var sut = this.sut();
sut.canAddModem();
}
It tells me Right.AddModem is undefined
When I try to stub the Right Enum with
sinon.stub(Right, "AddModem").returns(14);
I get the error
`D:\Repos\Complete\node_modules\angular\index.js:2
module.exports = angular;
^
source-map-support.js:445
ReferenceError: angular is not defined`
IN the habenero-identity module
i tried the angularcontext module, I tried importing angular, i tried putting it on the global variable...nothing works

using TypeScript service in both angularJs Controllers and TypeScript Controllers

After converting my AngularJS Service to TypeScript using the word "export", then makes it available for import in a TypeScript controller...
, but how can i still injecting it ,with old controllers?
Explaining in Detail , I am rewriting my controllers to services on Typescript to be prepared for a future migration of angularjs to angular 2.x,
Here is a service "equipmentAreaStorageT" using TypeScript...
<reference path="../../Scripts/typings/angularjs/angular.d.ts" />
import { UrlService } from '../../Scripts/app/services/urlService';
export class EquipmentAreaStorageT {
keyPrefix = "";
api = "";
index ="";
constructor(private isl3UrlService: UrlService) {
var _this = this;
this.keyPrefix = "EquipmentAreaStorageT";
this.api = "api/equipmentAreaApi/";
this.index = "EquipmentArea";
}
getIndexUrl() {
return this.isl3UrlService.getPath + this.index;
}
}
angular.module('main').service('equipmentAreaStorageT', EquipmentAreaStorageT);
and I know using the Import keyword should be enough for injecting this into a TypeScriptController
import { EquipmentAreaStorageT } from '../EquipmentArea/EquipmentAreaStorageT';
export class EquipmentAreaControllerT {
$inject = ["$scope"];
entity = {};
isOpen = false;
gridOptions = {};
isl3SelectionService = {};
isl3DialogService = {};
constructor($scope,private isl3EquipmentAreaStorage: EquipmentAreaStorageT) {
var _this = this;
var ctrl = $controller("baseEditOnGridController", { $scope: this, storage: isl3EquipmentAreaStorage});
ctrl.loadRecords();
}
}
angular.module('main').controller('EquipmentAreaControllerT', EquipmentAreaControllerT);
but i dont want to transform all my Controllers to Typescript.. not at the moment, so how can i use this new TypeScript service in my old .js controller. i have tryed this for example..
appRoot.controller("EquipmentAreaController", [
"$scope", "equipmentAreaStorageT"
function ($scope, equipmentAreaStorageT) {
$scope.entity = {};
$scope.isOpen = false;
$controller("baseEditOnGridController", { $scope: $scope, storage: equipmentAreaStorageT});
$scope.loadRecords();
}
]);
but i get always this error.
Object.defineProperty(exports, "__esModule", { value: true });
im working with visual studio and added the Types for working with typescript.
If you just import service in a controller - it wouldn't be the same as injecting. You can use imported value only for typescript typings.
You should properly set up your builder (webpack, gulp - whatever you use) to work with typescript. Everything still will be the same as with javascript. You still need to register service in some module and inject in another place.
If you are using AngularJs 1.5+ consider using components. Also look at ng-annotate (or it's babel plugin to simplify injection)

Cannot access Angular NG1 Service from Angular 2+ Component

I have tried every example I have found, and am still unable to call an NG1 Service from my Angular Component.
Is this even possible in the way I am describing below?
Service is defined like so:
'use strict';
angular.module('app.shared.services').factory('ng1TestService', ng1TestService);
function ng1TestService() {
var getGreeting = function () {
return "HELLO DOM! GOOD JOB!";
}
return {
getGreeting: getGreeting
}
}
I am calling upgrade on this service in my component:
upgradeAdapter.upgradeNg1Provider('ng1TestService')
Component Constructor:
constructor(#Inject('ng1TestService') ng1TestService : any) {
var hello = ng1TestService.getGreeting();
}
PROBLEMS:
I get an error saying that there is no Provider for ng1Test Service
I cannot call the NG1 Service
I had to add the "any" cast to resolve an error
It is not possible for me to add this Service to my "Providers" list since it is not in TS format
Any input would be appreciated.
Thanks!

Simple service based on Observable with Angular 1.5

I would like to use Rxjs in my project which is based on Angular 1.5 and written in ECMA 5. I would like to rewrite my service methods which are based on promises and want implement Observables.
I write sth like this in my service:
function service(Restangular) {
var self = this;
self.user = new Rx.Subject();
var service = {
artistStream: artistStream,
};
function artistStream(artist) {
self.user.onNext({
data : Restangular
.all('text/')
.customGET('search', {q : artist})
});
}
return service;
}
And then I tried use this service in my component like this :
function testRx(artist) {
console.log(artistService.artistStream(artist));
}
I get error from console :
TypeError: self.user.onNext is not a function
What I'm doing wrong? It is my first time when I use Observables
Ok, rewrite service and work properly.
function artistStream(artist) {
const promise = Restangular
.all('text/')
.customGET('search', {q : artist})
const subscription = Rx.Observable.fromPromise(promise);
return subscription;
}

Resources