Daniel Zarioiu Daniel Zarioiu - 3 months ago 99
TypeScript Question

How to add a delay for Angular 2 HTTP calls

I have the following problem

I'm using Angular 2 with TypeScript to implement a web application that uses HTTP calls to a REST Server. Now the problem is that some GET calls are faster than others 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';

@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 type of delay doesn't work */
setTimeout(() => {}, 2000); // insert there the delay
/* when I go to Manufacturer the Get call will start */
this.goToManufacturer();
}

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

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

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:

{{variableWithYourData}}