2
respostas

Dúvida - Angular parte 3: upload, build e novos componentes - 03 Preview de imagens

Pessoal eu não consigo ver o preview da imagem, baixei o código do professor e está exatamente igual. Alguém pode me ajudar ?

Não da erro no console e não exibe a imagem.

( estou usando Google Chrome )

  • photo-form.component.html

    <div class="container">
    <form [formGroup]="photoForm" class="row" (submit)="upload()">
      <div class="col-md-6 text-center">
        <div class="form-group" *ngIf="!preview; else previewImage">
    
          <button  [immediateClick] type="button" (click)="fileInput.click()" class="btn btn-primary">
            <i class="fa fa-image fa-4x align-middle"></i>
          </button>
    
          <input #fileInput hidden formControlName="file" type="file" accept="image/*"
            (change)="handleFile($event.target.files[0])">
    
            <ap-vmessage text="Please, select a photo" *ngIf="photoForm.get('file').errors?.required">
          </ap-vmessage>
        </div>
    
        <ng-template #previewImage>
          <div class="text-center">
            <ap-photo [url]="preview" title="Preview">
            </ap-photo>
          </div>
        </ng-template>
      </div>
    
      <div class="col-md-6">
    
        <textarea formControlName="description" class="form-control form-control-sm"
          placeholder="photo description"></textarea>
    
        <app-vmessage text="Max length is 300" *ngIf="photoForm.get('description').errors?.maxlength">
        </app-vmessage>
    
        <div class="form-group">
          <label class="text-muted">
            Allow comments
            <input formControlName="allowComments" type="checkbox">
          </label>
        </div>
    
        <button [disabled]="photoForm.invalid" type="submit" class="btn btn-primary btn-block">
          Upload
        </button>
    
        <a class="btn btn-secondary btn-block">Cancel</a>
      </div>
    </form>
    </div>
  • photo-form.component.ts

import { PhotoService } from './../service/photo-service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-photo-form',
  templateUrl: './photo-form.component.html',
  styleUrls: ['./photo-form.component.css']
})
export class PhotoFormComponent implements OnInit {

  photoForm: FormGroup;
  file: File;
  preview: string;

  constructor(private formBuilder: FormBuilder, private photoService: PhotoService, private router: Router) { }

  ngOnInit(): void {
    this.photoForm = this.formBuilder.group({
      file: ['', Validators.required],
      description: ['', Validators.maxLength(300)],
      allowComments: [true]
    })
  }

  upload() {
    // Este metodo "this.photoForm.getRawValue();" traz todas as propriedades de uma unica vez do formulario
    // const photoFormData = this.photoForm.getRawValue();
    // photoFormData.file = this.file;
    // this.photoService
    //   .upload(photoFormData.description, photoFormData.allowComments, photoFormData.file)
    //   .subscribe(() => this.router.navigate(['']))

    const description = this.photoForm.get('description').value;
    const allowComments = this.photoForm.get('allowComments').value;
    this.photoService
      .upload(description, allowComments, this.file)
      .subscribe(() => this.router.navigate(['']))
  }

  handleFile(file: File) {
    this.file = file;
    const reader = new FileReader();
    reader.onload = (event: any) => this.preview = event.target.result;
    reader.readAsDataURL(file);
  }
}
  • photo.component.ts
const CLOUD = 'http://localhost:3000/imgs/'

@Component({
  selector: 'app-photo',
  templateUrl: './photo.component.html',
  styleUrls: ['./photo.component.css']
})
export class PhotoComponent {

  private _url = '';

  @Input() set url(url: string) {
    if (!url.startsWith('https://http.cat/images/')) {
      this._url = CLOUD + url;
    } else {
      this._url = url;
    }
  }

  get url() {
    return this._url;
  }
}
  • photo-form.module.ts

@NgModule({
  declarations: [
    PhotoFormComponent
  ],

  imports: [
    CommonModule,
    ReactiveFormsModule,
    VMessageModule,
    FormsModule,
    RouterModule,
    PhotoModule
  ]
})

export class PhotoFormModule {

}
2 respostas

Fala ai Angelo, tudo bem? Olhando assim é bem complicado te ajudar, podemos deixar passar detalhes.

Posso te pedir um favor? Compartilha o projeto (e api) completo com a gente, assim fica mais facil simular e encontrar o problema.

Pode compartilhar através do Github ou Google Drive (zipado).

Fico no aguardo.

Essa parte do seu photo.component.ts está meio esquisita.

@Input() set url(url: string) {
    if (!url.startsWith('https://http.cat/images/')) {
      this._url = CLOUD + url;
    } else {
      this._url = url;
    }
  }

No meu ficou assim:

@Input() set url(url: string) {
    if(!url.startsWith('data')) {
      this._url=cloud + url;
    } else {
      this._url = url;
    } 
  }

Mas as próprias fotos também não deveriam aparecer, somente as enviadas, já que as com url em Base64 não seriam identificadas.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software