Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component, OnInit, Input, ChangeDetectionStrategy } from '@angular/core';
- import { FormBuilder, FormGroup, Validators } from '@angular/forms';
- import { User, UserConnection } from 'app/shared/models/user';
- import { Store } from '@ngrx/store';
- import * as moment from 'moment';
- import { AppStore } from 'app/shared/interfaces/store.interface';
- import * as UserActions from 'app/shared/states/user/actions';
- import { Group } from 'app/shared/models/group';
- import { FileUploader, FileLikeObject } from 'ng2-file-upload';
- import * as fromAuth from 'app/shared/states/auth';
- import { CustomValidators } from 'app/shared/validators/CustomValidators';
- import { AppSettings } from 'app/shared/app.settings';
- @Component({
- selector: 'polinet-profile-setting',
- templateUrl: './setting.component.html',
- changeDetection: ChangeDetectionStrategy.OnPush,
- })
- export class SettingComponent implements OnInit {
- @Input('profile') profile: User;
- @Input('profileConn') profileConn: UserConnection;
- @Input('groups') groups: Group[];
- imageChangedEvent: any = '';
- croppedImage: any = '';
- cropperReady = false;
- rForm: FormGroup;
- public showPassword: string;
- public uploaderConfiguration = {
- allowedMimeType: ['image/jpeg', 'image/png'],
- maxFileSize: 0.5 * 1024 * 1024,
- errorMessage: '',
- };
- public uploader: FileUploader = new FileUploader({
- autoUpload: true,
- allowedMimeType: this.uploaderConfiguration.allowedMimeType,
- maxFileSize: this.uploaderConfiguration.maxFileSize,
- url: AppSettings.API_ENDPOINT_USER_UPLOAD_AVATAR,
- });
- public hasBaseDropZoneOver;
- constructor(private fb: FormBuilder, private store$: Store<AppStore>) {}
- ngOnInit(): void {
- this.rForm = this.fb.group({
- name: [this.profile.name, Validators.compose([Validators.required, Validators.pattern(/^[a-zA-Zá-ú\s]{3,50}$/)])],
- surname: [
- this.profile.surname,
- Validators.compose([Validators.required, Validators.pattern(/^[a-zA-Zá-ú\s]{3,50}$/)]),
- ],
- passwords: this.fb.group(
- {
- password: ['', Validators.compose([Validators.pattern(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/)])],
- confirm_password: [
- '',
- Validators.compose([Validators.pattern(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/)]),
- ],
- },
- {
- validator: CustomValidators.Match('password', 'confirm_password'),
- },
- ),
- email: [this.profile.email, Validators.compose([Validators.required, Validators.email])],
- group: this.profile.group,
- });
- this.changeShowPassword();
- this.uploader.onBeforeUploadItem = item => (item.withCredentials = false);
- /* this.uploader.onAfterAddingFile = item => {
- const fileReader = new FileReader();
- fileReader.onloadend = e => {
- const imageData = fileReader.result;
- const avatar = imageData.split('base64,')[1];
- console.log('AVATAR! ', avatar);
- this.uploaderConfiguration = {
- ...this.uploaderConfiguration,
- errorMessage: '',
- };
- this.store$.dispatch(new UserActions.UpdateUser({ avatar } as User));
- };
- fileReader.readAsDataURL(item._file);
- }; */
- this.store$.select(fromAuth.getToken).subscribe(authToken => (this.uploader.authToken = `Bearer ${authToken}`));
- this.uploader.onWhenAddingFileFailed = (item, filter, options) =>
- this.onWhenAddingFileFailed(item, filter, options);
- }
- private onWhenAddingFileFailed(item: FileLikeObject, filter: any, options: any) {
- const allowedTypes = this.uploaderConfiguration.allowedMimeType.join();
- const imageSize = Math.round(item.size / 1024);
- const errors = {
- fileSize: `Tamaño máximo de la imagen excedido (${imageSize} Bytes de ${this.uploaderConfiguration.maxFileSize /
- 1024} Bytes permitidos)`,
- mimeType: `Formato: "${item.type} no es permitido. Formatos permitidos: "${allowedTypes}"`,
- };
- const errorMessage = errors[filter.name] || `Error desconocido: ${filter.name}`;
- this.uploaderConfiguration = {
- ...this.uploaderConfiguration,
- errorMessage,
- };
- }
- public fileOverBase(e: any): void {
- this.hasBaseDropZoneOver = e;
- }
- public updateProfile() {
- const user = {} as User;
- this.changeFieldInForm(user, 'name');
- this.changeFieldInForm(user, 'surname');
- this.changeFieldInForm(user, 'email');
- this.changeFieldInForm(user, 'group');
- this.hasFieldInForm(user, 'password');
- this.store$.dispatch(new UserActions.UpdateUser(user));
- }
- private changeFieldInForm(user: User, field: string) {
- if (this.rForm.value[field] !== this.profile[field]) {
- user[field] = this.rForm.value[field];
- }
- }
- private hasFieldInForm(user: User, field: string) {
- if (this.rForm.value[field]) {
- user[field] = this.rForm.value[field];
- }
- }
- public hasError(formField: string, validators: string[]): boolean {
- return (
- this.rForm.controls[formField].touched &&
- validators.some(validator => this.rForm.controls[formField].hasError(validator))
- );
- }
- hasErrorPassword(formField: string, validators: string[]): boolean {
- const control = (this.rForm.controls['passwords'] as FormGroup).controls.password;
- return control.touched && validators.some(validator => control.hasError(validator));
- }
- public changeShowPassword() {
- this.showPassword = this.showPassword === 'password' ? 'text' : 'password';
- }
- public isVisiblePassword() {
- return this.showPassword === 'text';
- }
- fileChangeEvent(event: any): void {
- this.imageChangedEvent = event;
- }
- imageCropped(image: string) {
- this.croppedImage = image;
- const avatar = this.croppedImage.split('base64,')[1];
- this.store$.dispatch(new UserActions.UpdateUser({ avatar } as User));
- }
- imageLoaded() {
- this.cropperReady = true;
- }
- imageLoadFailed() {
- console.log('Load failed');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement