Olá colegas e professores da Alura, como estão todos?
Cara, estou pra finalizar este curso, e encontrei este problema onde o upload nao vai. Creio ser na parte do post, talvez algum problema com os headers , não sei ao certo. Segue meu código e imagens:
animais.service.ts:
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of, throwError } from 'rxjs';
import { catchError, mapTo } from 'rxjs/operators';
import { environment } from 'environments/environment';
import { TokenService } from '../autenticacao/token.service';
import { Animais, Animal } from './animais';
const API = environment.apiURL;
const NOT_MODIFIED = '304';
@Injectable({
providedIn: 'root',
})
export class AnimaisService {
constructor(private http: HttpClient, private tokenService: TokenService) {}
listaDoUsuario(nomeDoUsuario: string): Observable<Animais> {
return this.http.get<Animais>(`${API}/${nomeDoUsuario}/photos`);
}
buscaPorID(id: number): Observable<Animal> {
return this.http.get<Animal>(`${API}/photos/${id}`);
}
excluiAnimal(id: number): Observable<Animal> {
return this.http.delete<Animal>(`${API}/photos/${id}`);
}
curtir(id: number): Observable<boolean> {
return this.http
.post(`${API}/photos/${id}/like`, {}, { observe: 'response' })
.pipe(
mapTo(true),
catchError((error) => {
return error.status === NOT_MODIFIED ? of(false) : throwError(error);
})
);
}
upload(descricao: string, permiteComentario: boolean, arquivo: File) {
const formData = new FormData();
formData.append('description', descricao);
formData.append('allowComments', permiteComentario ? 'true' : 'false');
formData.append('imageFile', arquivo);
return this.http.post(`${API}/photos/upload`, formData, {
observe: 'events',
reportProgress: true,
});
}
}
novo-animal.component.ts :
import { HttpEvent, HttpEventType } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { finalize } from 'rxjs/operators';
import { AnimaisService } from '../animais.service';
@Component({
selector: 'app-novo-animal',
templateUrl: './novo-animal.component.html',
styleUrls: ['./novo-animal.component.css'],
})
export class NovoAnimalComponent implements OnInit {
formularioAnimal!: FormGroup;
file!: File;
preview!: string;
percentualConcluido = 0;
constructor(
private animaisService: AnimaisService,
private formbuilder: FormBuilder,
private router: Router
) {}
ngOnInit(): void {
this.formularioAnimal = this.formbuilder.group({
file: ['', Validators.required],
description: ['', Validators.maxLength(300)],
allowComments: [true],
});
}
upload() {
const allowComments =
this.formularioAnimal.get('allowComments')?.value ?? false;
const description = this.formularioAnimal.get('description')?.value ?? '';
this.animaisService
.upload(description, allowComments, this.file)
.pipe(finalize(() => this.router.navigate(['animais'])))
.subscribe(
(event: HttpEvent<any>) => {
if (event.type === HttpEventType.UploadProgress) {
const total = event.total ?? 1;
this.percentualConcluido = Math.round(100 * (event.loaded / total));
}
},
(error) => console.log(error)
);
}
gravaArquivo(arquivo: any): void {
const [file] = arquivo?.files;
this.file = file;
const reader = new FileReader();
reader.onload = (event: any) => (this.preview = event.target.result);
reader.readAsDataURL(file);
}
}
Segue imagem da requisição: