【问题标题】:Ionic platform.exitApp() not saves localStorageIonic platform.exitApp() 不保存 localStorage
【发布时间】:2019-02-28 23:20:58
【问题描述】:

当我使用platform.exitApp() 时,对localStorage 的更改在执行退出之前所做的更改没有保存。

这是我的启动方式:

this.user.profileGetbyId(this.user.userdata.id)
                                .subscribe(res => {
                                    if(res && res.success) {

                                        localStorage.setItem('user', res.data);
                                        this.user.userdata = res.data;
                                        console.log(this.user.userdata);
                                        this.platform.exitApp();

                                        //temp decision
                                        // setTimeout(() => {
                                        //  this.platform.exitApp();
                                        // }, 500);

                                    }
                                })

这样,在exit() 启动之前,控制台显示我已经更新了用户,但是当我下次启动应用程序时,我拥有exit() 之前的用户。

我尝试的下一件事是使用setTimeout() 延迟调用exit。有了这个timeout,用户可以正确保存。

如果没有setTimeout(),我如何以正确的方式保持更改?

【问题讨论】:

    标签: javascript angular typescript ionic-framework ionic2


    【解决方案1】:

    this.storage.set 返回一个承诺,等待它解决并执行 退出。

    这是代码

    this.storage.set('user', res.data).then(data=>{
       this.user.userdata = res.data;
       this.platform.exitApp();
    })
    

    在localStorage中,设置前使用JSON.stringify

    localStorage.setItem("user", JSON.stringify(res.data));
    

    要从 localStorage 中获取值,请使用

    JSON.parse(localStorage.getItem("user"))
    

    【讨论】:

    • 如何使用 localStorage 而不是 @ionic-storage ?
    • localStorage 不返回承诺。它可以像这样简单 -> localStorage.set("user", JSON.stringify(res.data)); this.platform.exitApp();
    • 你能告诉我,@ionic-storage 可以与 localStorage 一起使用吗?
    • 是的,您可以通过添加此 app.module 导入 IonicStorageModule.forRoot({ name: '__mydb', driverOrder: ['localstorage','indexeddb', 'sqlite', 'websql'] })
    • 请问您为什么要通过离子存储使用 localStorage?
    【解决方案2】:

    this.storage.set() 返回一个承诺并在设置键和值时解析。 (见Documentation

    所以你需要像这样调用then

    this.storage.set('user', res.data).then(data => { 
        this.user.userdata = res.data;
        this.platform.exitApp();
    }
    

    【讨论】:

    • 如何使用 localStorage 而不是 @ionic-storage ?
    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多