0

I'm trying to implement services as classes as per this Ng Conf video Angular 1.3 meets Angular 2.0 - Michał Gołębiowski:

https://youtu.be/pai1ZdFI2dg?t=4m25s

I keep getting this error:

TypeError: Cannot read property 'prototype' of undefined

Code below:

var angular = window['angular'];
angular
    .module('myApp', [])
    .service('myService', [MyService])
    .directive('test', function (myService) {
        return {
            restricts: 'E',
            template: 'Directive output: {{ctrl.message}}',
            controllerAs: 'ctrl',
            controller: function () {
                this.message = myService.message;
            }   
        }
    });

/*
// Works
function MyService () {
  return {
      message: "service test"
    }
}
*/

// Does not work
class MyService {
  public message:string;
  constructor () {
    this.message = "service test by class";
  }
}

http://codepen.io/AshCoolman/pen/PPLONm?editors=001

EDIT: Solution

Simple wrapping the class works, and that will do for now:

.service('myService', function () {return new MyService()})

Actually it seems quite straight forward now I think of it. The example video is using es6 perhaps with Babel, while I'm using Typescript. At a guess, Typescript/Tracuer is probably doing things differently. I will look into this later tonight and post a full explanation.

EDIT: Explanation

Martin Vseticka beat me to it, see below.

1 Answer 1

1

The line

.service('myService', [MyService])

should be

.service('myService', MyService)

Edit: The solution is more simple I guess :-) The approach with

function MyService () {
  return {
      message: "service test"
    }
}

works because functions are hoisted in JavaScript.

However, the following TypeScript code

class MyService {
  public message:string;
  constructor () {
    this.message = "service test by class";
  }
}

is transpiled to:

var MyService = (function () {
    function MyService() {
        this.message = "service test by class";
    }
    return MyService;
})();

which means that .service('myService', MyService) cannot work because MyService is not defined (i.e. MyService = undefined) at that point!

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

2 Comments

Ah yes, that looks odd, but its just the remenants of injection annotations I removed for the example. Previously .service('myService', ['$http', MyService]). It doesnt seem to be the problem.
Hoisting, shoulda guessed >_< Thanks mate

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.