import { Component, OnInit, ViewChild } from '@angular/core'; import { NgForm } from '@angular/forms'; import { Router, ActivatedRoute } from '@angular/router'; import { EditcategoryService } from './editcategory.service'; @Component({ selector: 'app-editcategory', templateUrl: './editcategory.component.html', styleUrls: ['./editcategory.component.css'] }) export class EditcategoryComponent implements OnInit { @ViewChild('editcategoryform', { static: true }) form: NgForm; uploadedFiles: Array = []; showMessage = false; text = ''; category: any; catId: string; constructor( private router: Router, private activedRoute: ActivatedRoute, private editcategoryService: EditcategoryService, ) { } ngOnInit() { this.activedRoute.paramMap.subscribe(paramMap => { if (paramMap.has('catid')) { this.catId = paramMap.get('catid'); this.editcategoryService.getCategoryById(this.catId) .subscribe(data => { const aux: any = data; if (aux.resp) { this.category = aux.category; this.form.controls.title.setValue(this.category.name); this.form.controls.subtitle.setValue(this.category.subname); } else { this.router.navigateByUrl('/main/category'); } }); } else { this.router.navigateByUrl('/main/category'); } }); } fileChange(element) { this.uploadedFiles = element.target.files; } onAccept() { if (this.form.valid) { this.showMessage = false; const name = this.form.value.title; const subname = this.form.value.subtitle; this.editcategoryService.updateCategory(this.catId, name, subname) .subscribe(data => { const aux: any = data; if (aux.resp) { if (this.uploadedFiles.length > 0) { let formData = new FormData(); for ( let i = 0; i < this.uploadedFiles.length; i++) { formData.append('uploads[]', this.uploadedFiles[i], this.uploadedFiles[i].name); } const extension = this.uploadedFiles[0].name.substring(this.uploadedFiles[0].name.length - 3).toLowerCase(); if (extension !== 'jpg' && extension !== 'png') { this.showMessage = true; this.text = 'Solo imagenes JPG o PNG'; } else { this.showMessage = false; this.editcategoryService.updatePicture(this.catId, formData) .subscribe(() => { this.router.navigateByUrl('/main/category'); }); } } else { this.router.navigateByUrl('/main/category'); } } else { this.showMessage = true; this.text = "Una categoria con ese titulo existe"; } }); } else { this.showMessage = true; this.text = "Titulo y sub titulo no pueden estar vacios"; } } onCancel() { this.router.navigateByUrl('/main/category'); } }