photo.service.ts
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Photo } from "./photo";
const API = 'http://localhost:3000';
@Injectable({ providedIn: 'root' })
export class PhotoService {
constructor(private http: HttpClient) {}
listFromUser(userName: string) {
return this.http
.get<Photo[]>(API + '/' + userName + '/photos');
}
listFromUserPaginated(userName: string, page: number) {
const params = new HttpParams()
.append('page', page.toString());
return this.http
.get<Photo[]>(API + '/' + userName + '/photos', { params });
}
upload(description: string, allowComments: boolean, file: File) {
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 { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { PhotoService } from '../photo/photo.service';
import { Router } from '@angular/router';
@Component({
selector: 'ap-photo-form',
templateUrl: './photo-form.component.html',
styleUrls: ['./photo-form.component.css']
})
export class PhotoFormComponent implements OnInit {
photoForm: FormGroup;
file: File;
constructor(
private formBuilder: FormBuilder,
private photoService: PhotoService,
private router: Router) { }
ngOnInit() {
this.photoForm = this.formBuilder.group({
file: [
'',
Validators.required
],
description: [
'',
Validators.maxLength(300)
],
allowComments: [
true
]
})
}
upload() {
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(['']))
}
}
Estou recebendo o erro :
Failed to load resource: the server responded with a status of 401 (Unauthorized)