amb-imagenes.component.ts 2.32 KB
import { Component, OnInit } from '@angular/core';
import { appSettings } from 'src/etc/AppSettings';
import { ProductoService } from 'src/app/services/producto.service';
import { Producto } from 'src/app/wrappers/producto';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-amb-imagenes',
  templateUrl: './amb-imagenes.component.html',
  styleUrls: ['./amb-imagenes.component.scss']
})

export class AmbImagenesComponent implements OnInit {

  apiUrl = appSettings.apiUrl;
  articulos: Producto[] = [];
  private auxProductos: Producto[] = [];
  private searchTerm: string = '';

  constructor(private productoService: ProductoService, private http: HttpClient) {}

  ngOnInit() {

    this.productoService.getAll().subscribe((productos: Producto[]) => {
      this.articulos = productos;
      this.filterItems();
    });
  }

        this.articulos = productos;
        this.filterItems();
      }, error => console.error(error));
  }

  onFileSelected(event, articulo: Producto) {

    let auxFiles: FileList = event.target.files;
    Array.from(auxFiles).forEach(file => {

      this.onLoad(file)
        .then(result => {

          articulo.imagenes.push({
            name: file.name,
            fromGallery: true,
            imagen: result,
            id_articulo: articulo.id
          });

          this.saveInBase({
            name: file.name,
            base64: result,
            codigo: articulo.CodArt,
            sector: articulo.CodSec
          });
        });
    })
  }

  filterItems() {

    this.auxProductos = this.articulos.filter(x => {
      return x.DET_LAR.toLowerCase().includes(this.searchTerm.toLowerCase())
    });
  }


  saveInBase(img) {

    this.productoService.saveInBase(img)
      .subscribe(data => {

      }, error => console.error(error));
  }

  onLoad(file) {

    return new Promise((resolve, reject) => {

      var fr = new FileReader();

      fr.onload = function() {

        resolve(fr.result);
      };

      fr.readAsDataURL(file);
    });

  }

  deleteImage(imagenes, index: number) {

    if (!imagenes[index].name) {
      imagenes[index].name = imagenes[index].imagen;
    }

    this.productoService.deleteImage(imagenes[index])
      .subscribe(res => {

        if (res) {
          imagenes.splice(index, 1);
        }
      }, error => console.error(error));
  }

}