Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  52] [ 2]  / answers: 1 / hits: 52196  / 7 Years ago, wed, july 26, 2017, 12:00:00

I'm quite new with Angular so what I need is to show a spinner each time when a http request is done.



I have many components:



<component-one></component-one>
<component-two></component-two>
<component-three></component-three>
<component-n></component-n>


Each one has a http request that get or save some data so when the http request is made I want to show my <loading></loading> component so I suppose is not a good practice injecting my loading component in each other component with a http request. Can I add a filter or something from angular that allows me to load the <loading> component automatically in each component that has an http request?



Also when the http request is done I want to show a message like Done or someting.



If anyone can provide me a solution for that I'll really appreciate, ty.


More From » html

 Answers
89

UPD: plunker. Take a look at app.ts. Sorry for having everything in a single file.



In Angular 4.3 there is a new HttpClientModule which supports interceptors. The main idea is to have something like this:



@Injectable()
export class LoadingIndicatorService {

private _loading: boolean = false;

get loading(): boolean {
return this._loading;
}

onRequestStarted(): void {
this._loading = true;
}

onRequestFinished(): void {
this._loading = false;
}
}


And then you just apply the logic from Christopher's answer to your HttpInterceptor.



The only thing you should be aware of are simultaneous request. This can be solved for example by generating a unique identifier to each request and storing it somewhere until the request is finished.



Then you can have a global LoadingIndicator component which injects LoadingIndicatorService.



For more details on HttpClientModule: https://medium.com/codingthesmartway-com-blog/angular-4-3-httpclient-accessing-rest-web-services-with-angular-2305b8fd654b


[#56969] Monday, July 24, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austonjuancarlosb

Total Points: 238
Total Questions: 89
Total Answers: 99

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;