Search code examples
angularangular-routing

Angular routing delay


I am fairly new to Angular so still getting used to the routing functionality.

I have a click through wizard and on the final step, there is a 'Complete' button which should post to the DB and route the user to a certain page. However, I have a timing issue in that the user is routed to the page before the DB insert is completed, meaning the page doesn't show their newly created review.

    next() {
        this.reviewOutput.emit(this.formGroup.value);
        delay(1000);
        this.router.navigate(['/reviews']);
    }

The /reviews component selects all the user's reviews from the DB upon loading, but this is being done before the review has been added to the DB.

Adding the delay of 1 second solves the issue but isn't very 'clean' nor is it good practice I imagine. Is there a 'better' way to solve this issue?

EDIT: The parent component also gets data from another child component so it needs to be the one that does the POST API call.


Solution

  • Call the API and return the response as an observable. On successful response from the subscription, you can redirect to the required component.

    data.service.ts :

    I assume you have a POST API and you're passing the review as payload.

    addReview(review: string): Observable<ApiResponse> {
        return this.http.post<ApiResponse>(
            // Your POST API,
            review,
            httpOptions
        )
    }
    

    app.component.ts :

    this.dataService.addReview(this.formGroup.value).subscribe(
        response => {
            console.log("Response :",response)
            // On success, route to reviews
            this.router.navigate(['/reviews']);
        },error => {
            console.log('Error :',error)
        }
    );