将浏览器存储绑定到Angular2中的视图

时间:2016-01-25 05:08:47

标签: angular web-sql

我使用webSql数据库来存储数据,我想将存储的数据绑定到Angular2中的视图,即如果存储的数据发生更改,则更改应自动反映在视图中。 有什么想法或建议吗?

1 个答案:

答案 0 :(得分:1)

您无法将属性直接绑定到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(),然后完成“绑定”,如果存储发生更改,您的视图将会更改。

完成上述操作的第二种方法是从WebSQLService类的update createdelete方法触发“事件”。然后您的组件可以监听它,然后重新获取更改。或者更有效的是,事件可以将更改传递给侦听器,该侦听器将直接更新myProp而不会读取其他数据库。

正如您所看到的,这是基本模式,但您必须选择实施。