0

There's no method with the Angular2 router to output all the routes, so what I have done is defined a Service to output the routes like so...

export class Route {
        constructor(
            public path: string,
            public component: any
        ) {}
    }

    @Injectable()
    export class RouteService {

        public static getRoots(): Route[] {
            return [
                 { path: '/', component: HomeComponent },
                { path: '/about-me', component: AboutMeComponent },
                { path: '/food', component: FoodComponent },
                { path: '/photos', component: PhotosComponent },
                { path: '/technology', component: TechnologyComponent },
                { path: '/blog', component:BlogComponent }
            ];
        }
    }

Now I use this in my main.ts like so @Routes(RouteService.getRoots()) and everything seems to work, however I would like to use the same service to define a variable so I can loop through the array of routes... like so

export class NavigationComponent {

    public routes: Route[];

    constructor(private router:Router, private routeService: RouteService) {

       // just write this to the console for now
       console.log(routeService.getRoots());
    }

    // more code here, etc....

However this produces an error in the console routeService.getRoots is not a function and my app crashes! What must I do so I can use the service in the @Routes() section of my main.ts whilst using the service in other components. I really don't know where I am going wrong as Angular2 is bending my mind right now!

1 Answer 1

2

Because the method getRoots() is marked as static. If you need it to be static, you have to call it like so: RouteService.getRoots(). Otherwise just remove the static keyword.


EDIT: You don't have an instance of your service in the @Routes() section, so you will need a static method there. Since all you do is calling a static method, you also don't need to inject it in the constructor anymore.

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

3 Comments

And there is no point in injecting it if the members are static.
However when I remove the statickeyword, I then error in the main.ts - routes_1.RouteService.getRoots is not a function(…) so I am unable to use the service in the @Routes() section of my main.ts
If you remove the static keyword, you have to call the method with your instance routeService.getRoots(). But on the other hand, I guess you don't have an instance of the class in the @Routes() section.

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.