My objective is to implement a spinner functionality whenever an HTTP request occurs in my Angular app. Essentially, I want the user to see a loading screen during these requests within my app component. The setup for my spinner component and spinner service files follows the solution outlined in this question.
The component code snippet from my app.component is as shown below:
@Component({
selector: 'todoApi',
template: `
<div class="foo">
<spinner-component></spinner-component>
<h1>Internship Project</h1>
<a [routerLink]="['Dashboard']">Dashboard</a>
<a [routerLink]="['Tasks']">List</a>
<router-outlet></router-outlet>
<div>
`,
directives: [ROUTER_DIRECTIVES,SpinnerComponent],
providers: [
ROUTER_PROVIDERS,
]
})
@RouteConfig([
{
path: '/dashboard',
name: 'Dashboard',
component: DashboardComponent,
useAsDefault: true
},{
path: '/tasks',
name: 'Tasks',
component: TaskComponent
},{
path: '/detail/:id',
name: 'TaskDetail',
component: TaskDetailComponent
},
])
In summary, I aim to display the spinner whenever an HTTP request is triggered within one of these routes. I understand this might be a basic query, but being new to Angular 2, I would greatly appreciate any guidance on this matter.
Thanks a lot!
Edit!:
Solution implemented with reference to Günther's answer:
I encapsulated my http
and spinner-service
functionalities into a new HttpClient
component, which I then utilized instead of the standard http module. Here is the code snippet for my custom HttpClient
component:
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { SpinnerService} from './spinner-service';
@Injectable()
export class HttpClient {
constructor(
private http: Http,
public spinner: SpinnerService
){
}
createAuthorizationHeader(headers:Headers) {
headers.append('Authorization', 'Basic ' + btoa('username:password'));
}
get(url) {
this.spinner.start();
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.get(url, { headers: headers }).do(data=> {this.spinner.stop()});
}
post(url, data) {
this.spinner.start();
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.post(url, data, { headers: headers }).do(data=> {this.spinner.stop()});
}
}