Я пытаюсь добавить изображение в форму регистрации и создать компонент загрузки, в который я добавлю HTML-кнопку загрузки.
Я создал компонент внутри app / shared / forms / image-upload/upload.
Вот код файла upload.component.ts:
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { HttpErrorResponse } from '@angular/common/http';
import { UploadEvent, UploadFile } from '../../../file-drop';
import { SortingService } from '../../../services/sorting.service';
import { FileService } from '../../../../api';
import { File } from '../../../../api/models';
import { NotificationsService } from '../../../../shared/notifications';
import { forEach } from '@angular/router/src/utils/collection';
@Component({
selector: 'repo-upload',
templateUrl: './upload.component.html',
styleUrls: ['./upload.component.scss']
})
export class UploadComponent{
@Input() parentFormGroup: FormGroup;
@Input() file: File;
@Output()
public onImageChange: EventEmitter<File> = new EventEmitter<File>();
public imageList: UploadFile[];
private imageMimeTypes: string[] = ['image/jpeg', 'image/png', 'image/gif'];
constructor(private formBuilder: FormBuilder, private sortingService: SortingService, private fileService: FileService, private notificationsService: NotificationsService) {
this.imageList = this.sortingService.list;
}
ngOnInit() {
this.parentFormGroup.addControl('images', this.formBuilder.array([], Validators.required));
}
/**
* add image to the file uploader
*
* @param event
*/
handleImageAdd(event: UploadEvent) {
for (let i = 0; i < event.files.length; i++) {
let formControl = new FormControl();
this.images.push(formControl);
let uploadFile = event.files[i];
let error: any;
if (!this.imageMimeTypes.includes(uploadFile.file.type)) {
error = error || {};
error.mimes = true;
}
// Size is given in bytes
if (uploadFile.file.size > 10000000) {
error = error || {};
error.max = true
}
if (error) {
formControl.setErrors(error);
}
}
this.checkFormValidity();
this.sortingService.addAll(event.files);
this.handleImageSave(event);
}
handleImageSave(event) {
//iterate through each uploaded image, save it and remove it from the file dropper
this.imageList.forEach((uploadFile, index, imageList) => {
let fileFormData = new FormData();
fileFormData.append('file', uploadFile.file);
this.fileService.save(fileFormData)
.subscribe(
(file) => {
this.notificationsService.success('Image saved successfully!');
imageList.splice(index);
this.onImageChange.emit(file);
},
(err: HttpErrorResponse) => {
if (err.status === 422) {
console.log(err);
}
}
);
});
}
removeImage(index: number) {
this.sortingService.remove(index);
this.images.removeAt(index);
this.checkFormValidity();
}
private checkFormValidity() {
if (this.images.length > 0) {
this.images.setValidators([]);
} else {
this.images.setValidators([Validators.required]);
}
this.images.updateValueAndValidity();
}
get images() {
return this.parentFormGroup.get('images') as FormArray;
}
}
Теперь проблема в том, что когда я использую <repo-upload></repo-upload>
внутри моего signup-form.component.html
файла, то страницаничего не показывать.
Когда я заглядываю в консоль страницы, я получаю сообщение об ошибке.Смотрите скриншот:
Может кто-нибудь помочь мне с этой проблемой.Я пытаюсь за последний день исправить это.
РЕДАКТИРОВАТЬ:
Я забыл добавить этот компонент в файл app.module.ts.После добавления его в файл app.module.ts я получаю сообщение об ошибке:
Uncaught Error: Type UploadComponent is part of the declarations of 2 modules: SharedModule and AppModule! Please consider moving UploadComponent to a higher module that imports SharedModule and AppModule. You can also create a new NgModule that exports and includes UploadComponent then import that NgModule in SharedModule and AppModule.
РЕДАКТИРОВАТЬ:
Вот мой файл app.module.ts:
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { RECAPTCHA_SETTINGS, RecaptchaModule, RecaptchaSettings } from 'ng-recaptcha';
import { RecaptchaFormsModule } from 'ng-recaptcha/forms';
import { AgmCoreModule } from '@agm/core';
import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';
import { Ng4LoadingSpinnerModule } from 'ng4-loading-spinner';
import { DeviceDetectorModule } from 'ngx-device-detector';
import { environment } from '../environments/environment';
import { ApiModule, ProfileService, PropertyService } from './api';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AuthModule } from './auth';
import { DummyComponent } from './dummy.component';
import { InterceptorsModule } from './interceptors';
import { LoginComponent } from './login/login.component';
import { NavbarComponent } from './navbar/navbar.component';
import { NotFoundComponent } from './not-found/not-found.component';
import { ProfileComponent } from './profile/profile.component';
import { SharedModule } from './shared';
import { UserModule } from './user';
import { SignupFormComponent } from './user/signup-form/signup-form.component';
import { PropertySearchFormComponent } from './property/property-search-form/property-search-form.component';
import { PropertyViewComponent } from './property/property-view/property-view.component';
import { SearchComponent } from './search/search.component';
import { SearchResultlistComponent } from './search/search-resultlist/search-resultlist.component';
import { SearchResultComponent } from './search/search-result/search-result.component';
import { ProfileSearchFormComponent } from './profile/profile-search-form/profile-search-form.component';
import { ProfileViewComponent } from './profile/profile-view/profile-view.component';
import { ProfileEditComponent } from './profile/profile-edit/profile-edit.component';
import { ErrorComponent } from './error/error.component';
import { InquiriesComponent } from './inquiries/inquiries.component';
import { InquiryItemComponent } from './inquiries/inquiry-item/inquiry-item.component';
import { PropertyEditComponent } from './property/property-edit/property-edit.component';
import { PropertyComponent } from './property/property.component';
import { InquiryItemFormComponent } from './inquiries/inquiry-item-form/inquiry-item-form.component';
import { AccountComponent } from './user/account/account.component';
import { AccountViewComponent } from './user/account/account-view/account-view.component';
import { AccountEditComponent } from './user/account/account-edit/account-edit.component';
import { PasswordResetComponent } from './user/password-reset/password-reset.component';
import { PasswordResetSendComponent } from './user/password-reset/password-reset-send/password-reset-send.component';
import { PasswordResetSubmitComponent } from './user/password-reset/password-reset-submit/password-reset-submit.component';
import { UserAuthentificationComponent } from './user/user-authentification/user-authentification.component';
import { GlobalNotificationsDirective } from './global-notifications/global-notifications.directive';
import { SearchInfoWindowComponent } from './search/search-info/search-info-window/search-info-window.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { NgxIntlTelInputModule } from 'ngx-intl-tel-input';
import { TenantDetailComponent } from './profile/tenant-detail/tenant-detail.component';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
NavbarComponent,
SignupFormComponent,
DummyComponent,
PropertyComponent,
PropertySearchFormComponent,
PropertyViewComponent,
SearchComponent,
SearchResultlistComponent,
SearchResultComponent,
ProfileSearchFormComponent,
NotFoundComponent,
ProfileComponent,
ProfileViewComponent,
ProfileEditComponent,
ErrorComponent,
InquiriesComponent,
InquiryItemComponent,
PropertyEditComponent,
InquiryItemFormComponent,
AccountComponent,
AccountViewComponent,
AccountEditComponent,
PasswordResetComponent,
PasswordResetSendComponent,
PasswordResetSubmitComponent,
UserAuthentificationComponent,
GlobalNotificationsDirective,
SearchInfoWindowComponent,
DashboardComponent,
TenantDetailComponent,
],
imports: [
NgbModule.forRoot(),
AgmCoreModule.forRoot({
apiKey: environment.googleMapApiKey,
libraries: ["places"]
}),
BrowserModule,
FormsModule,
ReactiveFormsModule,
RecaptchaModule.forRoot(),
RecaptchaFormsModule,
AppRoutingModule,
ApiModule.forRoot(),
AuthModule.forRoot(),
InterceptorsModule,
SharedModule,
UserModule,
[FroalaEditorModule.forRoot(), FroalaViewModule.forRoot()],
[Ng4LoadingSpinnerModule.forRoot()],
DeviceDetectorModule.forRoot(),
BsDropdownModule.forRoot(),
NgxIntlTelInputModule
],
providers: [
{
provide: RECAPTCHA_SETTINGS,
useValue: { siteKey: environment.recaptchaSiteKey } as RecaptchaSettings
}
],
bootstrap: [AppComponent]
})
export class AppModule { }