javascript - How to transform an AngularJS 1 service into an Angular 2 service? -


i trying reuse working code angularjs 1 services written in plain javascript in angular 2 environment.

the services look, instance, following example:

(function () {     angular.module('myapp.mysubmodule').factory('myappmysubmodulenormalservice', ['someotherservice',         function (someotherservice) {             var internalstate = {                 somenumber: 0             };             var service = {};              service.somefunction = function () {                 internalstate.somenumber++;             };              someotherservice.getvalues().foreach(function (v) {                 service[v] = function () {                     console.log(v + internalstate.somenumber);                 };             });              return service;         }]); })(); 

i have found various examples of how convert angularjs 1 services angular 2 services (such this one), of have in common instead of service factory, have export class.

this should follows:

import { injectable } '@angular/core';  @injectable() export class myappmysubmodulenormalservice {     somefunction: function () {         // ?     } } 

now, question how incorporate internal state , dynamically added properties. way go in constructor, i.e. fill each instance of class upon initialization, so:

import { injectable } '@angular/core';  @injectable() export class myappmysubmodulenormalservice {     constructor() {         var internalstate = {             somenumber: 0         };         var service = {};          this.somefunction = function () {             internalstate.somenumber++;         };          this.getvalues().foreach(function (v) {             service[v] = function () {                 console.log(v + internalstate.somenumber);             };         });     } } 

or there other way? above works (save missing dependency injection, still have find out how in angular 2). however, wondering whether way because have not come across samples did of member initialization in constructor.

you can use same approach in angular factory providers:

  export function someservicefactory(someotherservice) {     var internalstate = {       somenumber: 0     };     var service = {};      service.somefunction = function () {       internalstate.somenumber++;     };      someotherservice.getvalues().foreach(function (v) {       service[v] = function () {         console.log(v + internalstate.somenumber);       };     });      return service;   };  @ngmodule({   providers: [     {       token: 'myappmysubmodulenormalservice',       usefactory: someservicefactory,       deps: ['someotherservice']     }   ] }) 

both in angular , angularjs value returned factory function cached.


Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -