Guide to incorporating a delay for Angular 2 HTTP requests

I am currently utilizing Angular 2 with TypeScript to create a web application that relies on HTTP calls to interact with a REST Server.

One issue I am facing is the inconsistent speed of GET calls, requiring me to add delays before some calls. How can I address this problem effectively and eliminate the need for such delays?

For instance, after deleting a Manufacturer (as shown in the code below), I need to return to the view displaying all Manufacturers (where I implement the GET call within ngOnInit()).

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute }   from '@angular/router';
import { DataService } from '../../../data/data.service';
import { CallManufacturerServices } from '../calls/calls.service';
import { ManufacturerClass } from '../class/manufacturer.class';

@Component({
    templateUrl: './app/inventory/manufacturer/view/view.component.html',
    styleUrls: ['./app/inventory/manufacturer/view/view.component.css'],
    providers: [CallManufacturerServices]
})

export class ViewComponent implements OnInit, OnDestroy {
    private sub: any;
    private ServerData: ManufacturerClass = {
        ManufacturerId: 0,
        ManufacturerName: 'N/D',
        ManufacturerWebSite: 'N/D'
    };

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private data: DataService,
        private calls: CallManufacturerServices) {
    }

    ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
            let id = +params['id'];
            this.getSingleManufacturer(id);
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }

    private getSingleManufacturer(id: number) {
        this.calls.GetSingleManufacturer(id).subscribe(
            (data) => {
                this.ServerData = data.json();
            },
            error => console.log(error),
            () => console.log('getSingleManufacturer complete!')
       );
    }

    private deleteManufacturer(_manufacturer: ManufacturerClass) {
        this.calls.DeleteManufacturer(_manufacturer.ManufacturerId).subscribe(
            error => console.log(error),
            () => console.log('deleteManufacturer complete!')
        );
        /* This kind of delay method does not work */
        setTimeout(() => {}, 2000); // Add the delay here
        /* The Get call will be initiated when navigating back to Manufacturer */
        this.goToManufacturer();
    }

    private goToManufacturer() {
        this.router.navigate(['/inventory/manufacturer']);
    }

    private goToEdit(manufacturer: ManufacturerClass) {
         this.router.navigate(['/inventory/manufacturer/edit', manufacturer.ManufacturerId]);
    }
}

Answer №1

To ensure proper navigation in Angular 2, it is recommended to wait for the request to be successfully completed before navigating. Implement this approach:

this.calls.DeleteManufacturer(_manufacturer.ManufacturerId).subscribe(
        undefined, // Handle onNext
        error => console.log(error), // Handle onError
        () => { // Handle onComplete
            console.log('deleteManufacturer process complete!');
            this.goToManufacturer();
        }
    );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deployment failure due to undetected development keys in gitignore

I have a TypeScript-coded Express server with three files for keys in the compiled and pre-compiled code: /// dev.ts - development keys const keys = { googleClientSecret: "GOOGLE_KEY", mongoURI: "mongodb+srv://MONGO_K ...

Dealing with the error message "The 'new' keyword requires a constructor signature when targeting a type that does not have one, resulting in an implicit 'any' type.ts(7009)"

Currently, I am in the process of migrating an outdated JavaScript library to TypeScript for integration into Vue 3. However, I encountered an error message that states: 'new' expression, whose target lacks a construct signature, implicitly has a ...

Verify your identity with Azure AD B2C within a NativeScript Angular application

Is there a way to integrate Azure AD B2C authentication into a NativeScript Angular mobile app? I'm looking to create a mobile application that integrates with my current web application for authentication utilizing Azure AD B2C. ...

Angular struggles to process the mapped type modifiers in Typescript during compilation

In my node.js project, I have successfully implemented a custom mapped type as follows: export type Mutable<T> = { -readonly [P in keyof T]: T[P]; }; However, when I tried to add the same code to an Angular 6 project, compilation failed with th ...

How to dynamically insert variables into a separate HTML file while creating a VS Code extension

Currently working on a vscode extension, I'm facing an issue with containing the html in a string (like this: https://github.com/microsoft/vscode-extension-samples/blob/main/webview-view-sample/src/extension.ts). It leads to a large file size and lack ...

Path for WebStorm file watcher's output

I'm in the process of setting up a Typescript project in WebStorm, where I want the files to be transpiled into a dist folder. This is my current project folder structure: projectroot/src/subfolder/subfolder/index.ts What I aim for is to have the f ...

Receive regular updates every week for an entire month using Javascript

How can I calculate the number of check-ins per week in a month using Javascript? I have been unable to find relevant code for this task. Specifically, I am interested in determining the total count of user check-ins on a weekly basis. For example, if a u ...

How to extract values of variables from a typescript file with gulp

I have a bunch of typescript files, and some of them export a constant called APIS. I'm attempting to access these exports (with the goal of combining them into one file), but for some reason it's not working. I know I must be making a mistake s ...

Angular 8 Observable: Managing User Objects

I recently developed a new service and attempted to call an API method (HTTP GET) to retrieve data, but I'm encountering an issue where not all the data objects from the API GET request are being displayed. angular-component.ts public allUsers$: Obs ...

Utilizing Angular 2 Observable for showcasing a seamless flow of real-time information

Currently, my Angular 2 Web application is utilizing a Couchbase Server as its database. The data communication occurs through WebAPIs that interact with the CouchBase server. As of now, I am uncertain if this method is optimal, but I am constantly polling ...

Incorporating a <script> tag in Angular 8 to reference an external JavaScript file from a different website

I am currently using Angular 8 and its CLI to develop my website. Issue: I need to include an external JavaScript file from a different website by adding a <script> tag, for example: <script src="https://www.wiris.net/demo/plugins/app/WIRISplugin ...

Stretch your fingers to endure the typing nightmare

I have incorporated the typings for the nightmare class found here in my project through npm install @types/nightmare To enhance the existing typings without altering the index.d.ts file in node_modules, I aim to add the action() and evaluate_now() method ...

Implementing unique union type in React: Effective ways to declare typescript type for prop value

I am currently facing an issue where I need to set a specific type for a prop value. However, the challenge lies in the fact that the types are string unions which can vary depending on the usage of the React Component. Let me provide you with the TypeScr ...

The element is not defined in the Document Object Model

There are two global properties defined as: htmlContentElement htmlContentContainer These are set in the ngAfterViewInit() method: ngAfterViewInit() { this.htmlContentElement = document.getElementById("messageContent"); this.htmlContentCont ...

Utilizing Angular2 Observables for Time Interval Tracking

I'm working on a function that needs to be triggered every 500ms. My current approach in angular2 involves using intervals and observables. Here's the code snippet I've implemented so far: counter() { return Observable.create(observer =&g ...

Building a custom dialog box using Angular Material with HTML and CSS

I've been exploring different approaches to create a customized angular material dialog with a unique header using CSS/SCSS and the TailwindCSS framework. I am aiming for a specific visual effect, similar to what is shown in the figure below. desired ...

Is it possible to combine two separate host listeners into a single function in Angular 2?

One solution is to combine 2 different host listeners into a single function so that it can be called whenever needed. @HostListener('window:unload', ['$event']) unloadHandler() { this.eventService.send({ name: 'onUnload' }) ...

Is it possible for TypeScript to mandate abstract constructor parameters?

This specific function is designed to take a constructor that requires a string argument and then outputs an instance of the constructed value T: function create<T>(constructor: new(value: string) => T): T { return new constructor("Hello& ...

What are the steps to deploy an Angular 2 application on my website?

Although I found a similar question on stack overflow regarding hosting an Angular 2 website, it didn't quite answer my specific query. After creating my first Angular 2 app, I am now looking to take it online. I currently have free websites on Wix an ...

When the frontend-maven-plugin executes the npm run build command, it encounters difficulty locating the package.json file

I am currently developing an application with a Spring Boot backend and an Angular frontend. To build the frontend, I am utilizing the frontend-maven-plugin in conjunction with Maven. However, when running "mvn spring-boot:run" command, an error is encount ...