How to insert a dictionary with foreach using observables?

Asked

Viewed 31 times

0

I am trying to create several people in my database when starting the application, but it is only creating the last user.

APP.COMPONENT

export class AppComponent implements OnInit {
    title = 'webwhatsapp';
    peoples: Array<People> = [
        { id: '0', name: 'THIAGO DE BONIS CARVALHO SAAD SAUD', avatar: 'assets/users/thiagobonis.jpg', messages: null },
        { id: '1', name: 'BILL GATES', avatar: 'assets/users/billgates.jpg', messages: null },
        { id: '2', name: 'STEVE JOBS', avatar: 'assets/users/stevejobs.jpg', messages: null },
        { id: '3', name: 'LINUS TORVALDS', avatar: 'assets/users/linustorvalds.jpg', messages: null },
        { id: '4', name: 'EDSGER DIJKSTRA', avatar: 'assets/users/dijkstra.jpg', messages: null },
    ];

    constructor(public peopleService: PeopleService) {}

    ngOnInit(): void {
        this.peoples.forEach((people: People) => this.peopleService.create(people));
    }
}

BACKEND SERVICE:

createPeople(people: People): Observable<People> {
    return this.getPeople(people.id).pipe(
        catchError((error) => throwError(error)),
        switchMap(() => {
            return this.httpClient.post<People>(this.SERVER_URL, people).pipe(
                map((data) => data),
                catchError((error) => throwError(error))
            );
        })
    );
}

1 answer

0


A solution for this case is you return observable in your service, make a map to a list of observables, so Voce can use forkJoin (link to the documentation https://rxjs.dev/api/index/function/forkJoin), example of use:

var listaObservables = this.peoples.map((people: People) =>  this.peopleService.create(people));

forkJoin(observables).subscribe(() => {
console.log("sucesso");
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.