Компонент Angular5 не работает в пользовательском модуле (при добавлении страницы зависает) - PullRequest
0 голосов
/ 23 мая 2018

Я импортировал следующие компоненты в admin.module.ts, и они отлично работают:

ManageSpecialistsComponent
ManageSpecialistComponent

Странная вещь, когда я пытаюсь добавить ReactiveModelFormComponent к администратору.module.ts это не работает.Однако, когда он добавлен в app.module.ts, он работает нормально.Когда я добавляю другие свежие компоненты в модуль admin.module.ts, они работают.Я подумал, что, возможно, мне нужно импортировать ReactiveFormsModule для ReactiveModelFormComponent в admin.module.ts, но простое добавление только этого модуля приводит к зависанию страниц.

Что я делаю неправильно?Все, что я пытаюсь сделать, это заставить ReactiveModelFormComponent работать в admin.module.ts для использования на страницах.

app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { RouterModule, Routes } from '@angular/router';
    import { HttpClientModule } from '@angular/common/http';
    import 'rxjs/Rx';

    import { AppComponent } from './app.component';
    import { LoginComponent } from './home/login.component';

    //base pages
    import { AboutComponent } from './pages/base/about/about.component';


    import { HomeComponent } from './pages/base/home/home.component';

    /* Feature Modules */
    import { UserModule } from './user/user.module';
    import { ExpenseModule } from './expense/expense.module';

    import { AdminModule } from './pages/admin/admin.module';


    /* common Modules */
    import { ToastrService } from './common/toastr.service';
    import { NavBarComponent } from './nav-bar/nav-bar.component';

    //for testing remove if not working
    //import { ReactiveModelFormComponent } from './reactive-model-form/reactive-model-form.component';
    //import { TestComponent } from './test/test.component';



    const appRoutes: Routes = [
      { path: 'login', component: LoginComponent},
      { path: 'about', component: AboutComponent},
      //{ path: 'form', component: ReactiveModelFormComponent},
      { path: '', redirectTo: 'login', pathMatch: 'full' },
      { path: '**', redirectTo: 'login', pathMatch: 'full' }
    ];


    @NgModule({
      imports: [
        AdminModule,
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        HttpModule,
        HttpClientModule,
        UserModule,
        ExpenseModule,
        RouterModule.forRoot(
          appRoutes
        )
      ],
      declarations: [
        AppComponent,
        HomeComponent,
        LoginComponent,
        AboutComponent,
        NavBarComponent

        //SpecialistZipComponent
      ],
      exports: [],
      bootstrap: [AppComponent],
      providers: [ToastrService]
    })
    export class AppModule { }

admin.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule} from '@angular/router';


import { AuthGuard } from '../../user/auth-guard.service';
import { AuthService } from '../..//user/auth.service';


import { ManageSpecialistComponent } from './manage-specialist/manage-specialist.component';
import { ManageSpecialistsComponent } from 'app/pages/admin/manage-specialists/manage-specialists.component';


import { AdminService } from './admin.service';
//may have to remove this service
import { SpecialistsSearchService } from './manage-specialists/specialists-search.service';



//this component does not work
import { ReactiveModelFormComponent } from '../../reactive-model-form/reactive-model-form.component';
//import { ReactiveFormsModule } from '@angular/forms';
import { Test2Component } from './test2/test2.component';

//try fix from stackoverflow for ReactiveModelFormComponent
import { CommonModule } from '@angular/common';




@NgModule({
  imports: [
    BrowserModule, CommonModule,
    RouterModule.forChild([
      //{ path: 'admin', component: Test2Component },
      { path: 'admin/manage-specialist/:id', component: ManageSpecialistComponent },

      { path: 'admin/manage-specialists', canActivate: [ AuthGuard], component: ManageSpecialistsComponent }
    ])
  ],
  declarations: [
    ManageSpecialistComponent,
    ManageSpecialistsComponent, ReactiveModelFormComponent
  ],
  //exports may need to be removed.. just a test
  exports: [
    ReactiveModelFormComponent
  ],
  providers: [

    AuthService,
    AuthGuard,
    AdminService,
    SpecialistsSearchService

  ]
})
export class AdminModule {}

реактивная модель-form.component.html (по запросу)

<input type="search"
       class="form-control"
       placeholder="Please enter search term"
       [formControl]="searchField">
<hr/>
<ul>
  <li *ngFor="let search of searches">{{ search }}</li>
</ul>

реактивная модель-form.component.ts

import {
  NgModule,
  Component,
  OnInit
} from '@angular/core';
import {
  ReactiveFormsModule,
  FormControl
} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import 'rxjs/Rx';

@Component({
  selector: 'app-reactive-model-form',
  templateUrl: './reactive-model-form.component.html',
  styleUrls: ['./reactive-model-form.component.css']
})
export class ReactiveModelFormComponent implements OnInit {

  constructor() { }

  searchField: FormControl;
  searches: string[] = [];

  ngOnInit() {
    this.searchField = new FormControl();
    this.searchField.valueChanges
        .debounceTime(400)
        .distinctUntilChanged()
        .subscribe(term => {
          this.searches.push(term);
          alert(term);
        });
  }
}

1 Ответ

0 голосов
/ 23 мая 2018

Проверьте это:

  1. В AppModule переместите рекомендуемый Модуль администрирования в конец импорта.
  2. BrowserModule просто нужно импортировать один раз в app.module.Для функциональных модулей импортируйте CommonModule .Источник: Angular Guide :
  3. Я думаю, вам также необходимо повторно добавить ReactiveFormsModule в модуль администратора, так как ваш компонент должен работать.

AdminModule

imports: [
CommonModule, 
FormsModule, 
ReactiveFormsModule,
RouterModule.forChild
 ]

AppModule

imports: [
BrowserModule
etc...
AdminModule

Надеюсь, это решит твою проблему, Адриан!

...