Beruflich Dokumente
Kultur Dokumente
that you want to send some specific headers with all of your requests. And
although you could use another package inside your app, you can also
easily add your own HTTP interceptor for this!
In this Quick Win we will add a custom HTTP interceptor which will
intercept all outgoing HTTP calls that our Ionic app makes. Inside those
requests we will use a token that we store and retrieve from the Ionic
Storage and also catch any errors that happens at the top most level inside
the app.
The result looks like the gif above if you inspect your HTTP calls and
headers, so let’s dive into it!
Starting our HTTP Interceptor Ionic
App
We don’t need any special packages for this but just a blank Ionic app and
an additional provider, so go ahead and run:
After this your provider will be automatically added to your module, but we
need to change it a bit. We want to provide it for
the HTTP_INTERCEPTORS so it looks just like the custom Ionic Error
handler. Also, we add
the HttpClientModule and IonicStorageModule to prepare
everything.
Go ahead and change yourapp/app.module.ts to:
Provide the Interceptor inside your ngModule
10
13
14 @NgModule({
15 declarations: [
16 MyApp,
17 HomePage
18 ],
19 imports: [
20 BrowserModule,
21 IonicModule.forRoot(MyApp),
22 IonicStorageModule.forRoot(),
23 HttpClientModule
24 ],
25 bootstrap: [IonicApp],
26 entryComponents: [
27 MyApp,
28 HomePage
29 ],
30 providers: [
31 StatusBar,
32 SplashScreen,
35 ]
36 })
Especially the last point is optional, I just wanted to show how you could
plug in some error mechanism at that place.
10 @Injectable()
12
14
17
19
20 return Observable.fromPromise(promise)
21 .mergeMap(token => {
23 return next.handle(clonedReq).pipe(
24 catchError(error => {
27
29 title: error.name,
30 message: msg,
31 buttons: ['OK']
32 });
33 alert.present();
34
36 return _throw(error);
37 })
38 );
39 });
40 }
41
44 if (token) {
46 clone = request.clone({
47 setHeaders: {
48 Accept: `application/json`,
49 'Content-Type': `application/json`,
51 }
52 });
53 return clone;
54 }
55
56 return request;
57 }
58 }
To test successful or failed requests we can also add 2 more functions, but
nothing of ths should be new to you so open
your pages/home/home.ts and change it to:
A dummy class for some HTTP calls
5 @Component({
6 selector: 'page-home',
7 templateUrl: 'home.html'
8 })
10
11 authenticated = false;
12 message = '';
13
15
16 setAuthState(authenticated) {
17 if(authenticated) {
19 this.authenticated = true;
20 });
21 } else {
22 this.storage.remove('my_token').then(() => {
23 this.authenticated = false;
24 });
25 }
26 }
27
28 getSuccessful() {
29 this.http.get('https://pokeapi.co/api/v2/pokemon/').subscribe(res => {
30 this.message = res['results'][0].name;
31 });
32 }
33
34 getFail() {
35 this.http.get('https://notvalid.xy').subscribe(
36 res => {}
37 ,err => {
38 this.message = err.message;
39 }
40 );
41 }
42 }
The final piece is to wire up some buttons, but the following code doesn’t
really needs any explanation at all besides that it goes into
your pages/home/home.html:
The view to test our functionality
1 <ion-header>
2 <ion-navbar color="primary">
3 <ion-title>
5 </ion-title>
6 </ion-navbar>
7 </ion-header>
9 <ion-content padding>
10
11 <ion-card text-center>
12 <ion-card-header>
14 </ion-card-header>
15 <ion-card-content>
16 {{ message }}
17 </ion-card-content>
18 </ion-card>
19
24
25 </ion-content>
Now you can make your authorised requests which will get the header
token added and the regular requests will not plus in case of an error you
directly see the alert that something went wrong with your request!
It’s actually not that hard to build your own logic for adding those kind of
things, but in a real environment you might need to make
the access/refresh token dance if a request fails or in the beginning of
your app check if a stored token is still valid.
You can also find a video version of this Quick Win below.