Add Models/Entities/Objects to NgModule in Angular 2

匆匆过客 提交于 2019-12-08 18:23:54

问题


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 { }

回答1:


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.



来源:https://stackoverflow.com/questions/40259357/add-models-entities-objects-to-ngmodule-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!