Below is a snippet of code from the Tour of Heros tutorial for Angular.io:
getHeroesSlowly(): Promise<Hero[]> {
return new Promise(resolve => {
// Simulate server latency with 2 second delay
setTimeout(() => resolve(this.getHeroes()), 2000);
});
}
The description states: To simulate a slow connection, import the Hero symbol and add the following getHeroesSlowly() method to the HeroService.
I understand that it is best practice to build websites based on slow connections with two examples of such being here and here.
But why would I set a timer to test the build (like the one that Angular suggests) instead of throttling the connection (say in Chrome)?
In your example the setTimeout
is used to simulate server response in two seconds. It doesn't necessarily mean that it simulates slow connection. A response can come in two seconds for various reasons, one being that server takes 2 seconds to complete its job. However, as you noticed, this is not production code and is used to demonstrate a specific feature of the framework.
The most common use for setTimeout
in production code is to allow Angular to run change detection once between actions that you would otherwise perform synchronously. In the article Everything you need to know about the ExpressionChangedAfterItHasBeenCheckedError
error this method is suggested as a possible solution to the error.
This is just a basic example of a slow connection with API, as you quoted, so you could see the loading data. Throttling the connection (in Chrome) as you said, would not simulate the delay of the connection between the API and the client, it would be slowing the whole web page.
More interesting would be using both tricks at the same time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With