I\'m using token based authentication and token is already saved on DB.
When app starts, I need to fetch the token from DB and make it available before making API ca
I have implemented above use case in this way.
I have created ApiService
for CRUD
like below.That code
is self-explanatory and if you need more info please let me know.
api-service.ts
import { Injectable, } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Headers, RequestOptions, BaseRequestOptions } from '@angular/http';
import { Storage } from '@ionic/storage';
import { Events } from 'ionic-angular';
@Injectable()
export class ApiService {
constructor(private http: Http, private storage: Storage, private events: Events) { }
createHeader(headers: Headers) {
return new Promise((resolve, reject) => {
this.storage.get('loggedInUser')
.then((token: any) => {
if (token) headers.append('Authorization', 'token ' + token.token);
resolve(headers);
}, err => {
resolve(headers);
});
});
}
get(api) {
let header = new Headers();
return Observable.fromPromise(this.createHeader(header))
.map(() => {
let options = new BaseRequestOptions();
options.withCredentials = true;
options.headers = header;
return options
})
.switchMap((options) => this.http.get(api, options))
.catch((err: Error | Response) => {
if (err instanceof Response && err.status === 401) {
this.events.publish('token-expiration');
}
return Observable.throw(err);
});
}
post(url, params): Observable {
return new Observable(observer => {
let header = new Headers();
this.createHeader(header)
.then(() => {
let options = new RequestOptions({ headers: header });
this.http.post(url, params, options)
.subscribe(response => {
observer.next(response);
observer.complete();
}, (e) => {
observer.error(e);
});
})
})
}
delete(url) {
return new Observable(observer => {
let header = new Headers();
this.createHeader(header)
.then(() => {
return this.http.delete(url, { headers: header, withCredentials: true })
.subscribe(response => {
observer.next(response);
observer.complete();
});
})
});
}
}
Here I have created loggedInUser
storage when the user logged into the app.It is also a provider
as shown below.
social-login.ts
import { Injectable } from '@angular/core';
import { ApiService } from "../providers";
import { LocalCacheServiceProvider } from "../local-cache-service/local-cache-service";
import { UserService } from "../user-provider";
import { Storage } from '@ionic/storage';
@Injectable()
export class SocialLoginProvider {
constructor(private apiService: ApiService, private localCacheService: LocalCacheServiceProvider, private userService: UserService, private storage: Storage) {
}
//login To App
loginToApp(url: string, data: string) {
this.apiService.post(url, { access_token: data })
.map((res: any) => res.json())
.subscribe(res => {
this.setUserLocally(res);
});
}
//set User Locally
setUserLocally(user) {
this.localCacheService.clearAllKeys().then(() => {
this.userService.setLoggedInUser(user);
this.storage.set('loggedInUser', user);
});
}
}
After that, I can consume above service (i.e. ApiService
) through any of my provider
(for CRUD
operations) as shown below.
This is the ArticleService
.
article-service.ts
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import { config } from '../config/config';
import { ApiService } from './api-service';
@Injectable()
export class ArticleService {
constructor(private apiService: ApiService) {
}
getBookById(id) {
return this.apiService.get(`${config.getBookById}${id}/`).map((res: any) => res.json());
}
}
Above approach works perfectly fine for me.Hope this approach will help you too.If you need more help please let me know.