在我的ionic2应用程序中,我需要存储用户信息,即使在用户关闭并重新打开应用程序后也可以使用它。因此我正在使用SqlStorage服务。
然而,代码非常冗长和丑陋:
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 :(得分:0)
您可以使用装饰器在运行时生成getter和setter。就类型系统而言,具有getter和setter以及普通属性的属性是相同的。因此,在运行时声明它们不会违反类型系统。
中的示例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;
}