2016-08-05 13 views
0

私のionic2アプリケーションでは、ユーザーがアプリケーションを閉じて再オープンしても使用できるようにユーザー情報を保存する必要があります。したがって、私はこれにSqlStorage Serviceを使用しています。コードはかなり長く、醜いですがTypescript(Ionic2)でゲッターとセッターを書く

import { Injectable } from '@angular/core'; 
import {Storage, SqlStorage} from 'ionic-angular'; 

@Injectable() 
export class Profile { 
    private _storage: any; 

    constructor(private _api: ApiEndpoint, private _uploadService: UploadService) { 
    this._storage = new Storage(SqlStorage); 
    } 

    get firstname(): string { 
    return this._storage.get('firstname'); 
    } 

    set firstname(value: string) { 
    this._storage.set('firstname', value); 
    } 

    get lastname(): string { 
    return this._storage.get('lastname'); 
    } 

    set lastname(value: string) { 
    this._storage.set('lastname', value); 
    } 

    get username(): string { 
    return this._storage.get('username'); 
    } 

    set username(value: string) { 
    this._storage.set('username', value); 
    } 

.... 
.... 
.... and so on for every field 

私の質問があり、このコードを書くための良い方法はありますか?

答えて

0

実行時にデコレータを使用してgetterとsetterを生成できます。型システムに関しては、getterとsetterを持つプロパティと通常のプロパティは同じです。したがって、実行時にそれらを宣言しても型システムに違反することはありません。ここで

TypeScript Playground

import { Injectable } from '@angular/core'; 
import {Storage, SqlStorage} from 'ionic-angular'; 

function Storage(target, propName: string) { 
    Object.defineProperty(target, propName, { 
     configurable: true, 
     get: function() { 
      return this._storage.get(propName); 
     }, 
     set: function(v) { 
      return this._storage.set(propName, v); 
     } 
    }); 
} 

@Injectable() 
export class Profile { 
    private _storage: any; 

    constructor(private _api: ApiEndpoint, private _uploadService: UploadService) { 
     this._storage = new Storage(SqlStorage); 
    } 

    @Storage 
    firstname: string; 
    @Storage 
    lastname: string; 
    @Storage 
    username: string; 
} 
の例です
関連する問題