Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Use module constructor to setup

Tags:

angular

I lazyload this feature module. It has different routes and the first one is the default route. As I need to setup a menu for this feature module I have tried to use the module constructor.

It works perfectly but is it semantically correct to use the module to setup data? I haven't see any example where someone used the same approach.

import {NgModule}      from '@angular/core';
import {Routes, RouterModule}  from '@angular/router';
import {OverviewComponent} from "@app/$/main/overview.component";
import {DetailComponent} from "@app/$/main/overview.component";
import {MenuService} from "@app/scheme/desk/menu/menu.service";

export const routes:Routes = [
    {
        path: "",
        redirectTo: "overview"
    },
    {
        path: "overview",
        component : OverviewComponent,
    },
    {
        path: "detail",
        component : DetailComponent
    }

];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    declarations:   [OverviewComponent, DetailComponent],
    exports: [RouterModule]
})
export class DeskModule {

    constructor(private menuService:MenuService){

        this.menuService.items = [{
            label: 'Overview',
        },
        {
            label: 'Detail',
        }];

    }

}
like image 402
Trevor Hector Avatar asked Mar 01 '17 10:03

Trevor Hector


1 Answers

Regardless of if it is Angular or any other Class in any language the question

but is it semantically correct to use the module to setup data?

holds true for any class.

Now a Angular module

  1. At its core is just a class which gets instantiated AND
  2. IMPORTANTLY You are allowed to inject services in the constructor you can do whatever you like using those services in the realms of what services should do.

Then the problem boils down to

Should a class setup its data in the constructor ?

A general best practice for constructors is to do minimal setup that is required for its objects to make it easier to perform heavy work such as interacting with outside resources.

So as long as your "data setup" is really private and lightweight you should not perform this initialization IMO. This is just one case for not doing data initialization at the Module level.

like image 86
bhantol Avatar answered Nov 03 '22 02:11

bhantol