Whisher Whisher - 17 days ago 5
AngularJS Question

angular1 es6 service with params

My goal is to get a service
with custom params

What's about ?

class ApartmentsGridPaginator {
constructor(pageSize, navRange, data) {}
}
//.service('ApartmentsGridPaginatorFactory', ApartmentsGridPaginatorFactory)
class ApartmentsGridPaginatorFactory {
getPaginator(pageSize, navRange,data){
return new ApartmentsGridPaginator(pageSize, navRange, data);
}
}
class ApartmentsController {
constructor(ApartmentsGridPaginatorFactory) {
'ngInject';

this.paginator = ApartmentsGridPaginatorFactory.getPaginator(30, 5, []);
}
}


Is there a better way ?

Answer

For classes that don't need to use DI service shouldn't be used.

Instead, the service may be defined as value and contain a constructor:

class ApartmentsGridPaginator {
  constructor(pageSize, navRange, data) {}
}

app.value('ApartmentsGridPaginator', ApartmentsGridPaginator);

...

class ApartmentsController {
  constructor(ApartmentsGridPaginator) {
    'ngInject';

    this.paginator = new ApartmentsGridPaginator(30, 5, []);
  }
}

Notice that the service follows established naming convention, injected item is a constructor and has PascalCase name.