Add Models/Entities/Objects to NgModule in Angular 2
Asked Answered
S

1

8

I've been trying to create an @NgModule (named ModelsModule) made of objects like User, Book, Library, Movie, and so on. Doing this I'm trying to not to import every object every time I need it but importing them at the beginning in the AppModule (main @NgModule) and use them as many times I want.

Objects/Entities/Classes... example

export class Author {
  constructor (
    public name: string,
    public avatar: string
  ) { }
}

ModelsModule

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { Author } from './author/author.model';
(...)

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    Author,
    Book,
    Movie,
    Store
  ],
})
export class ModelsModule {}

AppModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { MaterialModule } from '@angular/material';

import { AppComponent, SettingsDialog } from './app.component';

// THAT ONE
import { ModelsModule } from '../models/models.module';

@NgModule({
  declarations: [
    AppComponent,
    SettingsDialog
  ],
  entryComponents: [
    AppComponent,
    SettingsDialog
  ],
  providers: [
    // ModelsModule (?)
  ],
  imports: [
    BrowserModule,
    HttpModule,
    // ModelsModule (?)
    MaterialModule.forRoot()
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
Storey answered 26/10, 2016 at 10:7 Comment(2)
That's a good practice, and actually how angular-cli constructs things. What is the problem/question?Specification
You can't import simple classes to ngModule.Pimple
M
12

Model classes have no place in Angular. You just import the class into the file you need it, then use it.

import { MyModel } from './my.model';

class SomeComponent {
  model = new MyModel();
}

It seems a lot of newbies are confused about what the import statement are for in the class, and they think that they can somehow get rid of them by importing the class into Angular somehow. This is not the case. Importing the class into your file is nothing specific to Angular. File imports are simply a way for us to be able to use items from one file in another.

Moreta answered 26/10, 2016 at 10:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.