нежелательная страница автозагрузки в angular - PullRequest
0 голосов
/ 13 февраля 2020

после реализации управления загрузкой файлов в upoadImage () моя страница автоматически перезагружается, после загрузки происходит обновление sh, но я не вставил ни одного куска кода для этого. Как решить эту нежелательную функцию? Спасибо

sell-new-car.component.ts

import { Component, OnInit } from '@angular/core';
import * as _ from 'lodash';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { CarUploadService } from '../services/car-upload.service';
import { AuthenticationService } from '../services/authentication.service';
import { Observable, forkJoin } from 'rxjs';
import { HttpEventType, HttpEvent } from '@angular/common/http';

@Component({
  selector: 'app-sell-new-car',
  templateUrl: './sell-new-car.component.html',
  styleUrls: ['./sell-new-car.component.css']
})
export class SellNewCarComponent implements OnInit {

  observable: Observable<any>;

  imageError: string[] = [null, null, null];
  isImageSaved: boolean[] = [false, false, false];
  cardImageBase64: string[] = [null, null, null];
  fileToUpload = [null, null, null];
  imageUrl: string[] = [null, null, null];

  step:boolean[] = [true, false, false, false, false];
  uploading:boolean = false;

  // Size Filter Bytes
  max_size = 1048576; // 1MB
  allowed_types = ['image/png', 'image/jpeg'];
  height = 300;
  width = 300;

  detailsForm: FormGroup;
  carId: number;
  brand: any;
  model: any;
  userId: number;

  constructor(private formBuilder: FormBuilder, private carUploadService: CarUploadService, private authenticationService:AuthenticationService) { }

  ngOnInit() {

    this.detailsForm = this.formBuilder.group({
      brand: ['', Validators.required],
      model: ['', Validators.required],
    });

  }

  // convenience getter for easy access to form fields
  get f() { return this.detailsForm.controls; }

  fileChangeEvent(fileInput: any, formN:number) {

    this.imageError[formN] = null;
    this.cardImageBase64[formN] = null;
    this.isImageSaved[formN] = false;

    this.fileToUpload[formN] = fileInput.target.files[0];

    if (fileInput) {
/*
      if (fileInput.target.files[0].size > this.max_size) {
        //this.imageError = 'Maximum size allowed is ' + max_size / 1000000 + 'MB';
        this.imageError[formN] = 'Maximum size allowed is 1 MB';

        return false;
      }

      if (!_.includes(this.allowed_types, fileInput.target.files[0].type)) {
        this.imageError[formN] = 'Only Images are allowed ( JPG | PNG )';

        return false;
      }
   */
      const reader = new FileReader();
      reader.onload = (e: any) => {
        const image = new Image();
        image.src = e.target.result;
        image.onload = rs => {
          const img_height = rs.currentTarget['height'];
          const img_width = rs.currentTarget['width'];
/*
            if (img_height != this.height || img_width != this.width) {

              this.imageError[formN] = 'Dimentions allowed ' + this.height + '*' + this.width + 'px';

              return false;
            } else {

              this.cardImageBase64[formN] = e.target.result;
              this.isImageSaved[formN] = true;
              this.imageUrl[formN] = fileInput.target.files[0].name;

            }
            */

           this.cardImageBase64[formN] = e.target.result;
           this.isImageSaved[formN] = true;
           this.imageUrl[formN] = fileInput.target.files[0].name;
          };
      };

      reader.readAsDataURL(fileInput.target.files[0]);

    }
  }

  removeImage(formN) {
    this.cardImageBase64[formN] = null;
    this.isImageSaved[formN] = false;
  }

  saveDetails(){
    this.brand = this.detailsForm.controls['brand'].value;
    this.model = this.detailsForm.controls['model'].value;

    this.step[0] = false;
    this.step[1] = true;

  }

  uploadDetails(){

    this.uploading=true;
    this.userId = this.authenticationService.currentUserValue.id;

    this.carUploadService.uploadDetails(this.userId, this.model, this.brand).subscribe( data => {

      this.carId=data['carId'];

      this.uploadImages();

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

  }

  uploadImages(){

    const imagePath = 'CarsImages/';

    for(let i=0;i<this.imageUrl.length;i++){
      this.carUploadService.uploadImage(this.fileToUpload[i], i, imagePath+this.imageUrl[i], this.carId).subscribe((event:HttpEvent<any>) => {

        if (event.type === HttpEventType.UploadProgress) {
          const percentDone = Math.round(100 * event.loaded / event.total);
          console.log("progress=" + percentDone);
        }

        if (event.type === HttpEventType.Response) {
          if(event.status!=409){
            this.step[4] = false;
            this.step[5] = true;
            console.log('upload successful');
          }
        }

      });

      //INSERIRE LA GESTIONE DEGLI ERRORI

    }

  }

  nextStep(formN:number){

    if(formN == 0){
      this.step[1] = false;
      this.step[2] = true;
    }else if(formN == 1){
      this.step[2] = false;
      this.step[3] = true;
    }if(formN == 2){
      this.step[3] = false;
      this.step[4] = true;
      this.uploadDetails();
    }

  }
}

car-upload.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpEventType, HttpRequest, HttpEvent } from '@angular/common/http';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CarUploadService {

  constructor(private http:HttpClient) { }

  headers = {
    headers: new HttpHeaders({
      'Content-Type' : 'application/json',
      'Accept': 'application/json'
    })
  };

  headersImageBase64 = {
    headers: new HttpHeaders({
      'Content-Type': 'multipart/form-data'
    })
  }

  headersNo = {
    headers: new HttpHeaders({

    })
  }

  uploadDetails(userId, model, brand){

    return this.http.post('http://localhost:8080/uploadCarDetails?userId=' + userId +'&model=' + model +'&brand=' + brand, this.headers);

  }

  uploadImage(image:File, imageN, imageUrl, carId) {

    const progress = new Subject<number>();
    // this will be the our resulting map
    const status: { [key: string]: { progress: Observable<number> } } = {};

    const formData: FormData = new FormData();
    formData.append('image', image, image.name);

    //const req = new HttpRequest('POST', 'http://localhost:8080/uploadCarImage?' + 'imageN=' + imageN + '&imageUrl=' + imageUrl + '&carId=' + carId, formData, {reportProgress: true});
    //return this.http.request(req);
    return this.http.post<HttpEvent<any>>('http://localhost:8080/uploadCarImage?' + 'imageN=' + imageN + '&imageUrl=' + imageUrl + '&carId=' + carId, formData, { observe: 'events', reportProgress: true});
  }

}

stackoverflow говорит мне, что сообщение в основном закодировано, поэтому я добавляю что-то, чтобы обойти эту глупую автоматическую c функцию

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...