0

I'm migrating my angular app to typescript. I've got following ts code:

/// <reference path="../../../typings/tsd.d.ts" />

class UiRoutingHelper {
  constructor(public $state: any) {};

  reloadCurrentView() {
    return this.$state.go(this.$state.current.name, this.$state.params, {
      reload: true
    });
  };
}

mp.core.CoreModule.factory('UiRoutingHelper', ['$state', UiRoutingHelper]);

which does compiles correctly. The whole application build process builds correctly as well. But in the runtime I get following error:

Error: [$injector:undef] Provider 'UiRoutingHelper' must return a value from $get factory method.
http://errors.angularjs.org/1.3.15/$injector/undef?p0=UiRoutingHelper
    at angular.js:63
    at Object.enforcedReturnValue [as $get] (angular.js:4058)
    at Object.invoke (angular.js:4203)
    at angular.js:4021
    at getService (angular.js:4162)
    at Object.invoke (angular.js:4194)
    at extend.instance (angular.js:8493)
    at angular.js:7739
    at forEach (angular.js:331)
    at nodeLinkFn (angular.js:7738)

Please advice me on what am I doing wrong.

typings//tsd.d.ts is just a bootstrap file, which loads some predefined interfaces. mp.core.CoreModule has been declared before (it's available for TypeScript).

2 Answers 2

2

don't use a factory with a class. Just use a service. Code:

class UiRoutingHelper {
  constructor(public $state: any) {};

  reloadCurrentView() {
    return this.$state.go(this.$state.current.name, this.$state.params, {
      reload: true
    });
  };
}

mp.core.CoreModule.service('UiRoutingHelper', ['$state', UiRoutingHelper]);

Here is a video on the topic : https://www.youtube.com/watch?v=Yis8m3BdnEM

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

Comments

0

When using Typescript with Angular, factory registration expects a function that return a new instance of factory.

You can accomplish this by:

class UiRoutingHelper {
  static $inject = ['$state'];
  constructor(public $state: any) {};

  reloadCurrentView() {
    return this.$state.go(this.$state.current.name, this.$state.params, {
      reload: true
    });
  };
}

function factory(){
    return new UiRoutingHelper();
}

mp.core.CoreModule.factory('UiRoutingHelper', factory);

3 Comments

technically you're right. But it seems I shouldn't use factories. Just as @basarat wrote
Factory registration is awkward in Typescript. Services seems better in this situation. At the end, both are singleton and can perform same task
This Typescript code doesn't even compile. What about the ctor arguments?

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.