2017-07-04 53 views
-1

我想添加一个值到Angular中的现有对象,我从服务调用中获取对象,并在将其保存到本地存储之前,我想保存时间戳。添加键和值在Angular中的现有对象动态

我使用Object.assign为同一

的问题是,用户类型化与接口,如果我的任何属性添加到它说,该属性没有在接口中定义和接口类不被写入由我的Firebase用户信息。我不想编辑该界面或添加到它。我想动态地创建一个新的属性。

像Java中的反射一样,并在Javascript中添加动态值对象。

这就是我提前已经尝试

this.afAuth.authState.subscribe((data) => { 
    console.log("Here"); 
    if (data) { 
    const value = Object.assign(data,{TimeStamp : new Date().getTime()}); // this assign is not working even having obj in variable dosent help 
    console.log("Value"+JSON.stringify(value)); 
    localStorage.setItem("user", JSON.stringify(value)); 
    this.user = data; 
    this.service.fetchData(this.user.uid).subscribe((res) => { 
     this.comments = res; 
    }); 
    } else { 
    this.comments = null; 
    } 
}); 

任何帮助感谢

+2

...没有必要使用分配对象,如果对象存在,只是将它加入对飞'data.newProperty = someValue' – Alex

+1

,而不是'的console.log(“在这里”);'请尝试' console.log(data);'并粘贴输出的问题 – Dhyey

+0

你还没有确定具体的问题...或在这里问了一个问题 – charlietfl

回答

0

使用赋值为下面提到data.TimeStamp = new Date().getTime()才是正道。

this.afAuth.authState.subscribe((data) => { 
    console.log("Here"); 
    if (data) { 
    data.TimeStamp = new Date().getTime() // this assign is not working even having obj in variable dosent help 
    console.log("Value"+JSON.stringify(data)); 
    localStorage.setItem("user", JSON.stringify(data)); 
    this.user = data; 
    this.service.fetchData(this.user.uid).subscribe((res) => { 
     this.comments = res; 
    }); 
    } else { 
    this.comments = null; 
    } 
}); 
0

可以扩展火力地堡的用户界面,并添加时间戳,然后用你的扩展接口,取代默认的一个。

interface MyUser extends User { 
    timeStamp: any; 
} 

然后你可以时间戳添加到数据对象是这样的:

data.timestamp = {TimeStamp : new Date().getTime()} 
console.log("data",data); 

你并不需要使用Object.assign,你可以再补充一个值,一键直接在目的。

如果您将值作为字符串携带,使其成为字符串,但任何位置都是安全的起点,则您需要为接口中的timeStamp指定正确的类型。

请确保将您的本地用户变量输入到扩展接口。

public user: MyUser; 

this.afAuth.authState.subscribe((data) => { 
    console.log("Here"); 
    if (data) { 
    data.timestamp = {TimeStamp : new Date().getTime()} 
    console.log("data: "+JSON.stringify(data)); 
    localStorage.setItem("user", JSON.stringify(data)); 
    this.user = data; 
    this.service.fetchData(this.user.uid).subscribe((res) => { 
     this.comments = res; 
    }); 
    } else { 
    this.comments = null; 
    } 
}); 
+0

当我这样做,我得到编译中的另一个错误 说错误在 C:/用户/ c1xadmin/WebstormProjects/AngularConcepts/src /应用程序/ comment/comment.component.ts(80,16):属性'timestamp'在类型'User'上不存在。 我认为数据的类型是从火力类型的用户和一些打字稿如何能够推断不知道 –

+0

你必须投中的数据时,以MYUSER任何建议 - 这是用户的更广泛范围的情况下,所以它应该工作。我也建议在将其分配给本地this.user后,将其添加到返回的数据中。看到我上面的编辑。 –

+0

仍然是相同的错误错误什么可能是可能的原因 C:/Users/c1xadmin/WebstormProjects/AngularConcepts/src/app/comment/comment.component.ts(85,16):属性'时间戳'不存在on键入'User'。 ERROR在C:/Users/c1xadmin/WebstormProjects/AngularConcepts/src/app/comment/comment.component.ts(89,11):类型 '用户' 是不能分配给输入 'MYUSER'。 –

相关问题