Компонент является частью деклараций 2 модулей

Привет всем, у меня есть эта ошибка, я не знаю, как ее решить:

  • ОШИБКА в типе ClientsParComponent в C: /Users/pc/Documents/GitHub/livraison-app/angular/src/app/components/clients-par/clients-par.component.ts является частью объявлений двух модулей : ClientModule в C: /Users/pc/Documents/GitHub/livraison-app/angular/src/app/components/clients-par/client.module.ts и AppModule в C: / Users / pc / Documents / GitHub / livraison -app / angular / src / app / app.module.ts! Пожалуйста, подумайте о перемещении ClientsParComponent в C: /Users/pc/Documents/GitHub/livraison-app/angular/src/app/components/clients-par/clients-par.component.ts в модуль более высокого уровня, который импортирует ClientModule в C: / Users / pc / Documents / GitHub / livraison-app / angular / src / app / components / clients-par / client.module.ts и AppModule в C: / Users / pc / Documents / GitHub / livraison-app / angular / src /app/app.module.ts. Вы также можете создать новый NgModule, который экспортирует и включает ClientsParComponent в C: / Users / pc / Documents / GitHub /, создайте новый NgModule, который экспортирует и включает ClientsParComponent в C: / Users / pc / Documents / GitHub / livraison-app / angular /src/app/components/clients-par/clients-par.component.ts затем импортируйте этот NgModule в ClientModule в C: / Users / pc / Documents / GitHub / livraison-app / angular / src / app / components / clients- par / client.module.ts и AppModule в C: /Users/pc/Documents/GitHub/livraison-app/angular/src/app/app.module.ts.

это мой клиентский модуль;

import { ClientSortableDirective } from './client-sortable.directive';
import { ClientsParComponent } from './clients-par.component';
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { ClientRoutingModule } from './client-routing.module';
import { UIModule } from 'src/app/shared/ui/ui.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CKEditorModule } from '@ckeditor/ckeditor5-angular';
import { NgxMaskModule } from 'ngx-mask';
import { ClientparService } from '../services/clientpar.service';
import { NgbModule, NgbPaginationModule, NgbTypeaheadModule } from '@ng-bootstrap/ng-bootstrap';
import { NgApexchartsModule } from 'ng-apexcharts';


@NgModule({
  declarations: [ClientsParComponent],
  imports: [
    FontAwesomeModule,
    CommonModule,
    NgApexchartsModule,
    UIModule,
    FormsModule,
    ReactiveFormsModule,
    CKEditorModule,
    NgxMaskModule.forRoot(),
    HttpClientModule,
    NgbModule,
    ReactiveFormsModule,
    ClientRoutingModule,
    NgbPaginationModule,
    NgbTypeaheadModule





  ],

  providers: [ClientparService],


})
export class ClientModule { }

так выглядит мой проект:

введите описание изображения здесь

Моя модель рутирования клиента:

import { ClientsProComponent } from './../clients-pro/clients-pro.component';
import { NgModule, Component } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ClientsParComponent } from './clients-par.component';
import { AddClientComponent } from '../add-client/add-client.component';


const routes: Routes = [
  { path: 'clientpar', component: ClientsParComponent },
  { path: 'clientpro', component: ClientsProComponent },
  { path: 'addclient', component: AddClientComponent }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class ClientRoutingModule { }

Мой компонент:

import { ClientparService } from '../services/clientpar.service';
import { Component, OnInit, ViewChildren, QueryList } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { Observable } from 'rxjs';
import { Table } from './client.model';
import { ClientSortableDirective, SortEvent } from './client-sortable.directive';
import { tableData } from './data';

@Component({
  selector: 'clientpar',
  templateUrl: './clients-par.component.html',
  styleUrls: ['./clients-par.component.scss'],
  providers: [ClientparService, DecimalPipe]
})
export class ClientsParComponent implements OnInit {

  objectKeys;
  breadCrumbItems: Array<{}>;

  // Table data
  tableData: Table[];

  tables$: Observable<Table[]>;
  total$: Observable<number>;

  @ViewChildren(ClientSortableDirective) headers: QueryList<ClientSortableDirective>;
  constructor(private cpars: ClientparService) {
    this.tables$ = cpars.tables$;
    this.total$ = cpars.total$;
  }

  getclientpar() {
    this.cpars.getclientpar().subscribe(clientp => {
      this.tables$ = clientp as any;
    });
  }

  ngOnInit(): void {
    // this.objectKeys = Object.keys;
    // this.getclientpar();



    // tslint:disable-next-line: max-line-length
    // this.breadCrumbItems = [{ label: 'Shreyu', path: '/' }, { label: 'Tables', path: '/' }, { label: 'Advanced', path: '/', active: true }];

    /**
     * fetch data
     */
    this._fetchData();
  }

  /**
  * fetches the table value
  */
  _fetchData() {
    this.tableData = tableData;
  }

  /**
  * Sort table data
  * @param param0 sort the column
  *
  */
  onSort({ column, direction }: SortEvent) {
    // resetting other headers
    this.headers.forEach(header => {
      if (header.sortable !== column) {
        header.direction = '';
      }
    });
    this.cpars.sortColumn = column;
    this.cpars.sortDirection = direction;
  }
    }

Мой app.module.ts

import { NgbHighlight } from '@ng-bootstrap/ng-bootstrap';
import { ClientRoutingModule } from './components/clients-par/client-routing.module';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule, Component } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ErrorInterceptor } from './core/helpers/error.interceptor';
import { JwtInterceptor } from './core/helpers/jwt.interceptor';
import { FakeBackendProvider } from './core/helpers/fake-backend';
import { LayoutsModule } from './layouts/layouts.module';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ClientsParComponent } from './components/clients-par/clients-par.component';
import { ClientsProComponent } from './components/clients-pro/clients-pro.component';
import { CommandesComponent } from './components/commandes/commandes.component';
import { LivreursComponent } from './components/livreurs/livreurs.component';
import { ResponsablesComponent } from './components/responsables/responsables.component';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { AddClientComponent } from './components/add-client/add-client.component';
import { AddClientProComponent } from './components/add-client-pro/add-client-pro.component';
import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule } from '@angular/forms'
import { FlatpickrModule } from 'angularx-flatpickr';
import { ClientdireDirective } from './components/clients-pro/clientdire.directive';
import { AddresponsableComponent } from './components/addresponsable/addresponsable.component';
import { EditresponsableComponent } from './components/editresponsable/editresponsable.component';
import { ProfilComponent } from './components/profil/profil.component';
import { FinancesComponent } from './components/finances/finances.component';
import { InventaireComponent } from './components/inventaire/inventaire.component';
import { AddlivreurComponent } from './components/addlivreur/addlivreur.component';
import { EditlivreurComponent } from './components/editlivreur/editlivreur.component';
import { BanqueComponent } from './components/banque/banque.component';
import { ClientSortableDirective } from './components/clients-par/client-sortable.directive';



@NgModule({
  declarations: [
    AppComponent,
    ClientsParComponent,
    ClientsProComponent,
    CommandesComponent,
    LivreursComponent,
    ResponsablesComponent,
    AddClientComponent,
    AddClientProComponent,
    ClientdireDirective,
    AddresponsableComponent,
    EditresponsableComponent,
    ProfilComponent,
    FinancesComponent,
    InventaireComponent,
    AddlivreurComponent,
    EditlivreurComponent,
    BanqueComponent,
    ClientSortableDirective,


  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    LayoutsModule,
    AppRoutingModule,
    FontAwesomeModule,
    ClientRoutingModule,
    FormsModule,
    FlatpickrModule.forRoot(),
    NgSelectModule








  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },


    // provider used to create fake backend
    FakeBackendProvider,

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Моя модель рутирования приложения:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './core/guards/auth.guard';
import { LayoutComponent } from './layouts/layout.component';
import { ClientsParComponent } from './components/clients-par/clients-par.component';
const routes: Routes = [
  { path: 'account', loadChildren: () => import('./account/account.module').then(m => m.AccountModule) },
  // tslint:disable-next-line: max-line-length
  { path: '', component: LayoutComponent, loadChildren: () => import('./pages/pages.module').then(m => m.PagesModule), canActivate: [AuthGuard] },
  { path: '', component: LayoutComponent, loadChildren: () => import('./components/clients-par/client.module').then(m => m.ClientModule), canActivate: [AuthGuard] },
  { path: '', component: LayoutComponent, loadChildren: () => import('./components/clients-pro/clientpro.module').then(m => m.ClientproModule), canActivate: [AuthGuard] },
  { path: '', component: LayoutComponent, loadChildren: () => import('./components/commandes/commandes.module').then(m => m.CommandesModule), canActivate: [AuthGuard] },
  { path: '', component: LayoutComponent, loadChildren: () => import('./components/livreurs/livreurs.module').then(m => m.LivreursModule), canActivate: [AuthGuard] },
  { path: '', component: LayoutComponent, loadChildren: () => import('./components/responsables/responsables.module').then(m => m.ResponsablesModule), canActivate: [AuthGuard] },
];
@NgModule({
  imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'top' }),
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

person Abdeljabbar El Mediouni    schedule 24.07.2020    source источник
comment
Добавьте ClientsParComponent в свойство exports декоратора NgModule ClientModule. Удалите его полностью из AppModule. Добавьте ClientModule в свойство imports декоратора NgModule AppModule. Выполнено.   -  person Aluan Haddad    schedule 24.07.2020
comment
теперь я получаю эту ошибку: ОШИБКА в директиве Can't export ClientsParComponent в C: /Users/pc/Documents/GitHub/livraison-app/angular/src/app/components/clients-par/clients-par.component.ts из ClientModule в C: /Users/pc/Documents/GitHub/livraison-app/angular/src/app/components/clients-par/client.module.ts, поскольку он не был ни объявлен, ни импортирован! Невозможно определить модуль для класса ClientsParComponent в C: /Users/pc/Documents/GitHub/livraison-app/angular/src/app/components/clients-par/clients-par.component.ts! Добавьте ClientsParComponent в NgModule, чтобы исправить это.   -  person Abdeljabbar El Mediouni    schedule 24.07.2020
comment
Я не говорил вам удалять его из ClientModule declarations, я сказал вам добавить его в exports ClientModule.   -  person Aluan Haddad    schedule 24.07.2020
comment
Спасибо тебе большое, ты спас мне жизнь, я просто новичок в Angular   -  person Abdeljabbar El Mediouni    schedule 24.07.2020


Ответы (1)


Эта проблема в основном возникает, когда компонент объявлен в 2 разных модулях. В вашем случае вы объявляете ClientsParComponent в app.module.ts и даже в client.module.ts.

Итак, если вы удалите ClientsParComponent из declarations из app.module.ts, все будет работать так, как вы ожидаете.

Дополнительная информация. Поскольку в app-routing.module.ts вы уже выполняете отложенную загрузку, вы также можете удалить ClientsParComponent из импорта.

person Nav Kumar V    schedule 24.07.2020