将浏览器存储绑定到 Angular2 中的视图
Bind browser storage to the view in Angular2
我使用 webSql 数据库存储数据,我想将存储的数据绑定到 Angular2 中的视图,即,如果存储的数据发生变化,更改应自动反映在视图中。
有什么想法或建议吗?
您不能将 属性 直接绑定到 webSQL 数据库。相反,您需要将实现包装在一个服务中,然后在您的组件中使用该服务。
@Injectable()
export class WebSQLService{
read(){ ... }
create(){ ... }
update(){ ... }
delete(){ ... }
}
@Component({
template: `<input [ngModel]="myProp" (ngModelChange)="myProp = $value"/>`
})
export class MyComponent{
// Private property to hold the current value
private _myProp;
// Setter to propagate changes to the database automatically
set myProp(value){
this.updateSql(value);
this._myProp = value;
}
// Getter to get the current value of myProp
get myProp(){return this._myProp;}
// Inject the WebSQLService into your component to use
constructor(private webSqlService: WebSQLService){}
onInit(){
// Load the initial state for the component
this.webSqlService.read().then(x => this.myProp = x);
}
updateSql(value){
// Save the value to storage
this.webSqlService.update(value);
}
}
这基本上可以使您的存储和视图保持同步。您将需要一件我无法在此处提供的作品,如果存储中的值发生变化,这将是一种监听方式。这你可以在 WebSQL 文档中找到,然后简单地创建一个监听器,然后再次调用 this.webSqlService.read()
,然后完成 "binding",如果你的存储发生变化,你的视图也会改变。
完成上述任务的第二种方法是从 WebSQLService class 的 update
create
或 delete
方法触发 "Event"。然后您的组件可以收听它,然后重新获取更改。或者更有效地,事件可以将更改传递给侦听器,侦听器将直接更新 myProp
而无需读取另一个数据库。
如您所见,这是基本模式,但您必须选择实施方式。
我使用 webSql 数据库存储数据,我想将存储的数据绑定到 Angular2 中的视图,即,如果存储的数据发生变化,更改应自动反映在视图中。 有什么想法或建议吗?
您不能将 属性 直接绑定到 webSQL 数据库。相反,您需要将实现包装在一个服务中,然后在您的组件中使用该服务。
@Injectable()
export class WebSQLService{
read(){ ... }
create(){ ... }
update(){ ... }
delete(){ ... }
}
@Component({
template: `<input [ngModel]="myProp" (ngModelChange)="myProp = $value"/>`
})
export class MyComponent{
// Private property to hold the current value
private _myProp;
// Setter to propagate changes to the database automatically
set myProp(value){
this.updateSql(value);
this._myProp = value;
}
// Getter to get the current value of myProp
get myProp(){return this._myProp;}
// Inject the WebSQLService into your component to use
constructor(private webSqlService: WebSQLService){}
onInit(){
// Load the initial state for the component
this.webSqlService.read().then(x => this.myProp = x);
}
updateSql(value){
// Save the value to storage
this.webSqlService.update(value);
}
}
这基本上可以使您的存储和视图保持同步。您将需要一件我无法在此处提供的作品,如果存储中的值发生变化,这将是一种监听方式。这你可以在 WebSQL 文档中找到,然后简单地创建一个监听器,然后再次调用 this.webSqlService.read()
,然后完成 "binding",如果你的存储发生变化,你的视图也会改变。
完成上述任务的第二种方法是从 WebSQLService class 的 update
create
或 delete
方法触发 "Event"。然后您的组件可以收听它,然后重新获取更改。或者更有效地,事件可以将更改传递给侦听器,侦听器将直接更新 myProp
而无需读取另一个数据库。
如您所见,这是基本模式,但您必须选择实施方式。