我的目标是将类变量设置为会话存储值,如果该值存在于会话存储中。否则,变量将保留其默认值(在ngOnInit中设置)。

private getTableSessionItems = () => {
    var tSession = JSON.parse(sessionStorage.getItem('tableSession'));

    if(tSession){
        for (var property in tSession) {
            if (tSession.hasOwnProperty(property)) {
                tSession[property]; //Would like to set values equal here this.property = tSession[property]
            }
        }
        console.log('tableSession is true');
    }
    else{
        this.setTableSessionItems();
        console.log('nope keep trying', tSession);

    }
}

最佳答案

可以动态访问和更新当前类中的属性,如下所示:

private getTableSessionItems = () => {
    var tSession = JSON.parse(sessionStorage.getItem('tableSession'));

    if(tSession){
        for (var property in tSession) {
            if (tSession.hasOwnProperty(property)) {
                this[property] = tSession[property];
            }
        }
        console.log('tableSession is true');
    }
    else{
        this.setTableSessionItems();
        console.log('nope try again', tSession);

    }
}

关于javascript - Angular 2获取与此相关的所有变量。在 Controller 中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38960886/

10-12 03:56