2017-05-26 70 views
-1

通過下面的代碼,我得到了鍵和值對,我正在登錄控制檯。不過,我希望能夠將這些數據存儲在會話存儲中。在角2中的會話存儲中存儲鍵值

Object.keys(response).forEach(function (key) { 
    console.log(key,response[key]); 
}); 

我試過用這個Github的例子。使用下面的代碼,當我嘗試插入一個虛擬數據時它工作正常。

ngOnInit():void 
{ 
    this._propLoadService.getPropertyMap().subscribe(response=> { 
    this.loadPropValue=response; 
    this._storage.store('key','value'); 
    }); 
} 

但是當我使用下面的代碼增強for循環來存儲每個鍵值對從JSON響應,我收到錯誤。

ngOnInit():void 
{ 
    this._propLoadService.getPropertyMap().subscribe(response=> { 
    this.loadPropValue=response; 
    Object.keys(response).forEach(function (key) { 
     this._storage.store(key,response[key]); 
    }); 
    }); 
} 

,我正的錯誤是

ERROR TypeError: Cannot read property '_storage' of undefined 
at /main.bundle.js:449:21 
at Array.forEach (native) 
at SafeSubscriber._next (/main.bundle.js:448:35) 
at SafeSubscriber.__tryOrUnsub 
(/vendor.bundle.js:16394:16) 
at SafeSubscriber.next (/vendor.bundle.js:16343:22) 
at Subscriber._next (/vendor.bundle.js:16283:26) 
at Subscriber.next (/vendor.bundle.js:16247:18) 
at CatchSubscriber.Subscriber._next 
(/vendor.bundle.js:16283:26) 
at CatchSubscriber.Subscriber.next 
(/vendor.bundle.js:16247:18) 
    at MapSubscriber._next (/vendor.bundle.js:29484:26) 
    defaultErrorLogger @ core.es5.js:1084.. 

任何人可以幫助我一下,需要做什麼來指出。

回答

0

您是否嘗試過使用FAT Arrow功能像.forEach((key) => {...}

Object.keys(response).forEach((key) => { 
    this._storage.store(key,response[key]); 
}); 

我不知道,如果是thisthis._storage的引用變量,如果它指向的匿名函數的局部變量,當你」重新使用.forEach(function(key) {...}

+0

嗨馬科比,這爲我工作。非常感謝。 – Lkyashu

+0

沒問題我的朋友。如果您將我的答案標記爲解決方案,如果它對您有幫助,會很好:) –