1

Hi i have 'static class' Utils with only static methods (helpers):

export class Utils {    
     static doSomethingAndRedirect() {
         ...doo something...
         redirectTo->'/home'     
     }

}

So how redirectTo code should look like?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • 1
    You need a reference to the applications injector to be able to acquire a reference to the router. Just don't use a static method. – Günter Zöchbauer Oct 14 '16 at 10:46
  • i will be satisfy when someone give me answer also in pure js without angular2. Utils is my helper STATIC class - and I don't want to change it. Redirectin is so easy in js - there is a problem with angular2 ? – Kamil Kiełczewski Oct 14 '16 at 10:48
  • 2
    You try to stroke Angular2 against the grain, therefore no surprise you're not happy with it ;-) Angular2 is a new framework. Almost nothing about Angular1 applies to it. – Günter Zöchbauer Oct 14 '16 at 10:51
  • Why angular2 not support static methods? – Kamil Kiełczewski Oct 14 '16 at 10:53
  • 1
    Because they would need to build the whole framework in a different way and this would cause it to be less testable while testability is a main priority. – Günter Zöchbauer Oct 14 '16 at 10:55

2 Answers2

1

You have a wrong approach to the usecase you are trying to solve. Have a look at ngrx/store and ngrx/effects.

In short, you define actions and reducers which modify the state of your app. Next, you can react to different actions with different side-effects (ngrx/effects), for example in my app I have got:

  • Actions: LoginAction and LoginSuccessAction
  • Effects: when LoginSuccessAction is triggered, my effect redirects to /dashboard component

This makes for nice separation of concerns:

  • views display the current state and dispatch actions that change the state
  • actions specify what happens in the app
  • reducers specify what changes to state occur for different actions
  • effects specify what side-effects occur for certain actions
Alexander Ciesielski
  • 10,506
  • 5
  • 45
  • 66
  • Can you give more concrete solution for case described in my question? - How i should use ngrx in my Utils static class? – Kamil Kiełczewski Oct 14 '16 at 12:59
  • 1
    ngrx is a whole solution for managing state in the app, depending on your usecase it might be overkill. If you just want a utility class for small, common tasks, a `UtilityService` injected with `Router` might be want you want. – Alexander Ciesielski Oct 14 '16 at 13:01
0

The best solution that I found in my case was just... add parameter 'router' into static function argument list:

 static doSomethingAndRedirect(router) {
     ...doo something...

     router.navigateByUrl('home'); // redirect
 }

This is a kind of compromise between static helper convenience and non-static "angular way".

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345