Ionic 3如何确保在加载视图之前获取db数据

时间:2017-10-11 20:57:43

标签: angular typescript ionic-framework ionic3

我使用基于令牌的身份验证,令牌已保存在数据库中。

当应用程序启动时,我需要从DB获取令牌并在进行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
}

在加载视图之前,有什么方法可以确保获取数据库令牌并存储在共享服务中? storage.get是' ES6承诺'

关注是在加载视图升级到任何引导事件之前加载令牌的责任,因此onViewLoad不需要在每个组件中定义。

1 个答案:

答案 0 :(得分:4)

我已经以这种方式实现了上述用例。

我为ApiService创建了CRUD,如下所示。code是不言自明的,如果您需要更多信息,请告知我们。

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();
                        });
                })
        });
    }

}

我在用户登录应用时创建了loggedInUser存储空间。它还是provider,如下所示。

社交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);
    });
  }
}

之后,我可以通过我的ApiService任何操作(provider操作)使用以上服务(例如CRUD),如下所示。

这是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());
    }  
}

以上方法对我来说非常好。希望这种方法对你也有帮助。如果你需要更多帮助,请告诉我。