I wanted to use an HTTP interceptor so that every HTTP request has a delay of 500ms between the next one. I'm currently making these requests from an injectable service that is registered on the app.module and injected in my component. In the that same module I have registered my interceptor.
// delay-interceptor.ts
@Injectable()
export class DelayInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return timer(500).pipe(
delay(500),
switchMap(() => next.handle(request))
)
}
}
// app.module.ts
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: DelayInterceptor,
multi: true
},
ManageHousesService
]
// manage-houses.component.ts
createHouses() {
this.houses.foreach((house: House) => {
this.createHousesService.createHouse(house.name).subscribe(createdHouse => {
house.rooms.foreach((room: Room) => {
this.createHousesService.createRoom(house.id, room.name).subscribe();
});
});
});
}
// manage-houses.service.ts
createHouse(houseName: string): Observable<House> {
return this.httpClient.post(`${this.apiUrl}/houses`, { houseName: houseName });
}
createRoom(houseId: string, roomName: string): Observable<Room> {
return this.httpClient.post(`${this.apiUrl}/houses/${houseId}/rooms`, { roomName: roomName });
}
In my component I have to make requests in a nested way. I have a list of houses and for each house I want to create a list of rooms. So for each house I make a POST request and on the subscription I use the ID of the newly created house to create the rooms. For each room I make a POST request with the room information and the house ID. Now this is where the issue appears. Between each house request the delay is working, but between all the rooms of a house it is not, and I can't figure out why that's happening.
I suppose it might have something to do with calling the same method inside each foreach which will probably reuse the same observable or something similar, and thus not trigger the HTTP interceptor, but I'm not sure. On the interceptor I tried to use both the timer and the delay approach, but I got the same result with both approaches.
forkjoinorzipto accomplish the same result in a more reactive approach