Advertisement
Guest User

Untitled

a guest
May 15th, 2018
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.97 KB | None | 0 0
  1. import { Component, OnInit, Input, ChangeDetectionStrategy } from '@angular/core';
  2. import { FormBuilder, FormGroup, Validators } from '@angular/forms';
  3. import { User, UserConnection } from 'app/shared/models/user';
  4. import { Store } from '@ngrx/store';
  5. import * as moment from 'moment';
  6. import { AppStore } from 'app/shared/interfaces/store.interface';
  7. import * as UserActions from 'app/shared/states/user/actions';
  8. import { Group } from 'app/shared/models/group';
  9. import { FileUploader, FileLikeObject } from 'ng2-file-upload';
  10. import * as fromAuth from 'app/shared/states/auth';
  11. import { CustomValidators } from 'app/shared/validators/CustomValidators';
  12. import { AppSettings } from 'app/shared/app.settings';
  13.  
  14. @Component({
  15. selector: 'polinet-profile-setting',
  16. templateUrl: './setting.component.html',
  17. changeDetection: ChangeDetectionStrategy.OnPush,
  18. })
  19. export class SettingComponent implements OnInit {
  20. @Input('profile') profile: User;
  21. @Input('profileConn') profileConn: UserConnection;
  22. @Input('groups') groups: Group[];
  23. imageChangedEvent: any = '';
  24. croppedImage: any = '';
  25. cropperReady = false;
  26.  
  27. rForm: FormGroup;
  28. public showPassword: string;
  29. public uploaderConfiguration = {
  30. allowedMimeType: ['image/jpeg', 'image/png'],
  31. maxFileSize: 0.5 * 1024 * 1024,
  32. errorMessage: '',
  33. };
  34. public uploader: FileUploader = new FileUploader({
  35. autoUpload: true,
  36. allowedMimeType: this.uploaderConfiguration.allowedMimeType,
  37. maxFileSize: this.uploaderConfiguration.maxFileSize,
  38. url: AppSettings.API_ENDPOINT_USER_UPLOAD_AVATAR,
  39. });
  40. public hasBaseDropZoneOver;
  41.  
  42. constructor(private fb: FormBuilder, private store$: Store<AppStore>) {}
  43.  
  44. ngOnInit(): void {
  45. this.rForm = this.fb.group({
  46. name: [this.profile.name, Validators.compose([Validators.required, Validators.pattern(/^[a-zA-Zá-ú\s]{3,50}$/)])],
  47. surname: [
  48. this.profile.surname,
  49. Validators.compose([Validators.required, Validators.pattern(/^[a-zA-Zá-ú\s]{3,50}$/)]),
  50. ],
  51. passwords: this.fb.group(
  52. {
  53. password: ['', Validators.compose([Validators.pattern(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/)])],
  54. confirm_password: [
  55. '',
  56. Validators.compose([Validators.pattern(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/)]),
  57. ],
  58. },
  59. {
  60. validator: CustomValidators.Match('password', 'confirm_password'),
  61. },
  62. ),
  63. email: [this.profile.email, Validators.compose([Validators.required, Validators.email])],
  64. group: this.profile.group,
  65. });
  66. this.changeShowPassword();
  67. this.uploader.onBeforeUploadItem = item => (item.withCredentials = false);
  68.  
  69. /* this.uploader.onAfterAddingFile = item => {
  70. const fileReader = new FileReader();
  71. fileReader.onloadend = e => {
  72. const imageData = fileReader.result;
  73. const avatar = imageData.split('base64,')[1];
  74. console.log('AVATAR! ', avatar);
  75. this.uploaderConfiguration = {
  76. ...this.uploaderConfiguration,
  77. errorMessage: '',
  78. };
  79. this.store$.dispatch(new UserActions.UpdateUser({ avatar } as User));
  80. };
  81. fileReader.readAsDataURL(item._file);
  82. }; */
  83.  
  84. this.store$.select(fromAuth.getToken).subscribe(authToken => (this.uploader.authToken = `Bearer ${authToken}`));
  85. this.uploader.onWhenAddingFileFailed = (item, filter, options) =>
  86. this.onWhenAddingFileFailed(item, filter, options);
  87. }
  88.  
  89. private onWhenAddingFileFailed(item: FileLikeObject, filter: any, options: any) {
  90. const allowedTypes = this.uploaderConfiguration.allowedMimeType.join();
  91. const imageSize = Math.round(item.size / 1024);
  92. const errors = {
  93. fileSize: `Tamaño máximo de la imagen excedido (${imageSize} Bytes de ${this.uploaderConfiguration.maxFileSize /
  94. 1024} Bytes permitidos)`,
  95. mimeType: `Formato: "${item.type} no es permitido. Formatos permitidos: "${allowedTypes}"`,
  96. };
  97. const errorMessage = errors[filter.name] || `Error desconocido: ${filter.name}`;
  98. this.uploaderConfiguration = {
  99. ...this.uploaderConfiguration,
  100. errorMessage,
  101. };
  102. }
  103.  
  104. public fileOverBase(e: any): void {
  105. this.hasBaseDropZoneOver = e;
  106. }
  107.  
  108. public updateProfile() {
  109. const user = {} as User;
  110. this.changeFieldInForm(user, 'name');
  111. this.changeFieldInForm(user, 'surname');
  112. this.changeFieldInForm(user, 'email');
  113. this.changeFieldInForm(user, 'group');
  114. this.hasFieldInForm(user, 'password');
  115.  
  116. this.store$.dispatch(new UserActions.UpdateUser(user));
  117. }
  118. private changeFieldInForm(user: User, field: string) {
  119. if (this.rForm.value[field] !== this.profile[field]) {
  120. user[field] = this.rForm.value[field];
  121. }
  122. }
  123. private hasFieldInForm(user: User, field: string) {
  124. if (this.rForm.value[field]) {
  125. user[field] = this.rForm.value[field];
  126. }
  127. }
  128.  
  129. public hasError(formField: string, validators: string[]): boolean {
  130. return (
  131. this.rForm.controls[formField].touched &&
  132. validators.some(validator => this.rForm.controls[formField].hasError(validator))
  133. );
  134. }
  135. hasErrorPassword(formField: string, validators: string[]): boolean {
  136. const control = (this.rForm.controls['passwords'] as FormGroup).controls.password;
  137. return control.touched && validators.some(validator => control.hasError(validator));
  138. }
  139.  
  140. public changeShowPassword() {
  141. this.showPassword = this.showPassword === 'password' ? 'text' : 'password';
  142. }
  143. public isVisiblePassword() {
  144. return this.showPassword === 'text';
  145. }
  146. fileChangeEvent(event: any): void {
  147. this.imageChangedEvent = event;
  148. }
  149. imageCropped(image: string) {
  150. this.croppedImage = image;
  151. const avatar = this.croppedImage.split('base64,')[1];
  152. this.store$.dispatch(new UserActions.UpdateUser({ avatar } as User));
  153. }
  154. imageLoaded() {
  155. this.cropperReady = true;
  156. }
  157. imageLoadFailed() {
  158. console.log('Load failed');
  159. }
  160. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement