I'm still a newbie in programming and I apologize if the question may be stupid.
But i want to know how i can save data from a "get(url)" in an array. Once this data is in an array, I want to do the length of the array but when i do a "console.log to check the values and the length with "array.length" it always show "0".
In fact,after retrieving the length of the array, I would make a method to retrieve a random value to display a random faceSnap.
My problem is in the function : showOneFaceSnap()
import { Observable, Subject, Subscription } from 'rxjs';
import { FaceSnap } from './../models/face-snap.model';
import { Injectable } from "@angular/core";
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root' //on renregistre ce service à la racine de l'application
})
export class FaceSnapService {
// newFaceSnap$ = new Observable<FaceSnap[]>();
constructor(private http:HttpClient){
}
getAllFaceSnaps(): Observable<FaceSnap[]>{
// return this.faceSnaps;
return this.http.get<FaceSnap[]>('http://localhost:3000/facesnaps');
}
getFaceSnapById(faceSnapId: number): Observable<FaceSnap>{
// const faceSnap = this.faceSnaps.find(faceSnap => faceSnap.id===faceSnapId)
return this.http.get<FaceSnap>(`http://localhost:3000/facesnaps/${faceSnapId}`);
}
showOneFaceSnap(){
const faceTab = [];
this.http.get<FaceSnap[]>('http://localhost:3000/facesnaps').subscribe(facesnaps=>
facesnaps.forEach(data=> faceTab.push(data)) );
console.log("array ",faceTab, "array length ", faceTab.length );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>