1

What I would like to do is to create a model (e.g Book) in angular with ES6 that can be instantiated with some arguments (new Book('someTitle')). I have got it working with the following (suppose we need to inject something, such as $http):

function foo($http) {
   return class Book {
       constructor(title) {
           this.title = title;
       }
       fetch() {
           return $http.get('api/book/' + this.title);
       //...
       }
   };
}
angular.module('app')
    .service('Book', ['$http', function($http) {
        return foo($http);
    }];

The problem is this doesn't seem like a clean way of doing things. Also I'm not sure what problems could come out of it. Could anyone suggest a better way to achieve the same thing?

1
  • Why do you have a foo function? You could just return the class in the factory itself. That would make it more clear. This is how it's done in angular1. And by the way I dont really see how this question relates to es6. It would be the same using es5 classes. Commented Jul 30, 2016 at 11:33

1 Answer 1

1

I have done this in Typescript where instead of wrapping the class in a function, I have a static factory function which returns a factory for the class... which may look a bit cleaner. Looks something like this...

class Book {
   constructor(public $http) {}

   set(title) {
      this.title = title;
   }

   fetch() {
       return this.$http.get('api/book/' + this.title);
   }

   static factory () {
      let service = ($http) => {
         return new Book($http);
      }

      service.inject = ['$http'];
      return service;
   } 
}

angular.module('app')
       .service('Book', Book.factory());

Another way to get this to look really clean is what they did in Angular2 is with the ES2016/2017 decorators, which are currently working in Typescript. Anyway, just an idea!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply. I would like the model to be instantiated with title (e.g. new Book('someTitle'), but in your approach Book is constructed with $http and you need to call set(title) to set the title...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.