Acho que cometi algum erro, pois não estou conseguindo fazer o upload. Ao tentar chamar o método do upload recebo erro 401 Unauthorized do HTTP.
Segue abaixo o código:
--------------------
photo.service.ts
import { HttpClient, HttpParams } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { Photo } from "./photo";
const API = 'http://localhost:3000';
@Injectable({providedIn: 'root'})
export class PhotoService
{
constructor(protected http: HttpClient) {}
public listFromUser(userName: string) : Observable<Photo[]>
{
const url = API + '/' + userName.trim().toLowerCase() + '/photos';
return this.http.get<Photo[]>(url);
}
public listFromUserPaginated(userName: string, page: number = 1) : Observable<Photo[]>
{
const url = API + '/' + userName.trim().toLowerCase() + '/photos';
const params = new HttpParams().append('page', page.toString());
return this.http.get<Photo[]>(url, { params });
}
public upload(description: string, allowComments: boolean, file: File) : Observable<Object>
{
const formData = new FormData();
formData.append('description', description);
formData.append('allowComments', allowComments ? 'true' : 'false');
formData.append('imageFile', file);
return this.http.post(API + '/photos/upload', formData);
}
}
--------------------
photo-form.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { PhotoService } from '../photo/photo.service';
@Component({
selector : 'ap-photo-form',
templateUrl: './photo-form.component.html',
styleUrls : ['./photo-form.component.css']
})
export class PhotoFormComponent implements OnInit
{
public photoForm: FormGroup;
public file : File;
constructor(protected router: Router, protected formBuilder: FormBuilder, protected service: PhotoService) {}
public ngOnInit() : void
{
this.photoForm = this.formBuilder.group({
file : ['', Validators.required],
description : ['', Validators.maxLength(300)],
allowComments: [true],
});
}
public upload() : void
{
const description = this.photoForm.get('description').value;
const allowComments = this.photoForm.get('allowComments').value;
this.service
.upload(description, allowComments, this.file)
.subscribe(
() => this.router.navigate(['']),
error => console.log(error.message)
);
}
}
Aonde foi que eu errei?