amb-imagenes.component.ts 1.77 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();
    });
  }

  onFileSelected(event, articulo) {

    let file: File = event.target.files[0];

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

        articulo.imagenes = [];

        document.getElementById(articulo.CodSec + articulo.CodArt)['src'] = result;

        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.http.post(`${appSettings.apiUrl}/imagenes/guardar`, img)
      .subscribe(data => {
        console.log(data);
      });
  }

  onLoad(file) {

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

      var fr = new FileReader();

      fr.onload = function() {

        resolve(fr.result);
      };

      fr.readAsDataURL(file);
    });

  }
}