使用Angular2内存数据刷新后,本地存储不起作用

问题描述 投票:1回答:1

我正在关注这个图书馆:https://github.com/PillowPillow/ng2-webstorage

我的基础项目改编自Tours of Heroes

目前,我可以将值保存在本地存储中,并使用webstorage检索它们。但是,刷新后,我的值将恢复为存储在in-memory-data.service.ts中的旧值

bot.component.html:

<tr *ngFor="let bot of bots" routerLink="/botlevelup/{{bot.id}}">
    <td>{{bot.id}}</td>
    <td>{{bot.lastLevel}}</td>
    <td>{{bot.secondLevel}}</td>
</tr>

内存-data.service.ts:

import { InMemoryDbService } from 'angular-in-memory-web-api';

export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    const bots = [
     {"id":1,"lastLevel":5},
     {"id":2,"lastLevel":5},
     {"id":3,"lastLevel":5}
];
    return {bots};
  }
}

botlevelup.component.html

Bot: {{bot.id}}
Last Level: <input [(ngModel)]="bot.lastLevel" />
<button (click)="save()">Save</button>

botlevelup.component.ts

save() {
this.storage.store('boundValue', JSON.stringify(bot));
}

我可以看到我的更新值使用控制台日志存储在'boundValue'中,并且在刷新后仍然存在。

如何在刷新后从'boundValue'而不是原始的in-memory-data.service.ts中检索更新的值?

我想实现一个if else:

  1. 如果对bot 1和2进行了更改,它将从'boundValue'中检索
  2. 如果没有对bot 3进行任何更改,它将从in-memory-data.service中检索。

编辑#1:检索的代码片段

getBots(): Observable<Bot[]> {
        this.storage.retrieve('boundValue');
      return this.http.get<Bot[]>(this.botsUrl)
      .pipe(
      catchError(this.handleError('getBots', []))
    );
  }
angular local-storage web-storage
1个回答
0
投票

我设法根据机器人的更新值返回表格,如果没有更新,还可以返回机器人的旧值。

将机器人的原始值存储在本地存储中:

片段:

export const bots: Bot[] = [
 {"id":1,"lastLevel":5},
 {"id":2,"lastLevel":5},
 {"id":3,"lastLevel":5}
]

var local = JSON.stringify(bots);
this.storage.store('localstore', local);

为值更新创建本地存储,在问题是boundValue,它存储所有更改。

    this.storage.store('boundValue', JSON.stringify(bot));

从localstore和boundValue中检索值,检查boundValue中是否有更新,并将localstore替换为更新(如果有)。

    var newValues = this.storage.retrieve('boundValue');
    var oldValues = this.storage.retrieve('localstore ');

如果没有新值,则返回旧值。我为这些值使用变量'array':

if(boundValue == null){          
  var array = $.parseJSON(oldValues);
}

否则,更新数组中的旧值:

    else{
      var valueUpdate = $.parseJSON('[' + newValues + ']');
      var array       = $.parseJSON(oldValues); 

      for (var i=0; i<array.length; i++){
        for (var m=0; m<valueUpdate.length; m++){
          if (valueUpdate[m].id == array[i].id){
            array[i] = valueUpdate[m];
            break;  
          }
        }
      }       
   }

最后:

this.bots = array;

这可能不是最好的方式,但这是我能想到的。感谢所有关于我的问题的评论,这些评论让我了解了如何做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.