我正在使用基于令牌的身份验证,并且令牌已保存在数据库中.
当应用程序启动时,我需要从数据库中获取令牌并在进行API调用之前使其可用.
什么是最好的方法:
在组件中:
ngOnit() { storage.get('token').then((val) => { Make api call here }); }
或者在共享服务中:
getToken() { return Promise((resolve,reject)=>{ #if fetched once save in local var and resolve token #or fetch from DB and resolve token }) } // On Component this.sharedService.getToken().then((token)=>{ //Make api call }
有没有什么办法可以确保在加载视图之前获取DB令牌并存储在共享服务中? storage.get是’ES6承诺’
关注是在加载视图升级到任何引导事件之前加载令牌的责任,因此不需要在每个组件中定义onViewLoad.
我已经以这种方式实现了上述用例.
我已经为CRUD创建了ApiService,如下所示.该代码不言自明,如果您需要更多信息,请告诉我们.
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<any> { 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(); }); }) }); } }
在这里,我在用户登录app时创建了loggedInUser存储.它也是一个提供者,如下所示.
社会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); }); } }
之后,我可以通过我的任何提供程序(用于CRUD操作)使用上述服务(即ApiService),如下所示.
这是ArticleService.
文章-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()); } }