Daniel Zarioiu Daniel Zarioiu - 1 year ago 270
TypeScript Question

How to make an delay for Angular 2 HTTP calls

Hello I have the following problem:
I'm using Angular 2 with TypeScript to make a WebApplication that use HTTP calls to a Rest Server. Now the problem is that: the Get calls are too fast then other and I have to add some delay before them. How can I do that?

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';

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'

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

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

ngOnDestroy() {

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

private deleteManufacturer(_manufacturer: ManufacturerClass) {
error => console.log(error),
() => console.log('deleteManufacturer complete!')
/* this type of delay doesn't work */
setTimeout(() => {}, 2000); // insert there the delay
/* when I go to Manufacturer the Get call will start */

private goToManufacturer() {

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

For example after I delete one Manufacturer (see code), I have to go back to the view where I can see all the Manufacturers (there I implement the get call inside the ngOnInit()).

Answer Source

You can use setTimeout():

setTimeout(() => {
    //insert code you want to execute with delay
}, 4000); //delay you want to add in miliseconds (4000 ms = 4 seconds)

But, this is not recommended and you should avoid using this in your code if it's possible. You can use two-way data binding (interpolation) to update value of your variable in template, syntax is {{}} like this:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download