Angular 如何分解指向全局常量的对象?
在我的typescript文件中有以下方法Angular 如何分解指向全局常量的对象?,angular,typescript,Angular,Typescript,在我的typescript文件中有以下方法 this.userService.getUserById(this.userId).subscribe((user: any) => { }); 例如,如果我想从用户那里获得财产工资,我可以写 this.userService.getUserById(this.userId).subscribe((user: any) => { const salary = this.user.salary; }
this.userService.getUserById(this.userId).subscribe((user: any) => {
});
例如,如果我想从用户那里获得财产工资,我可以写
this.userService.getUserById(this.userId).subscribe((user: any) => {
const salary = this.user.salary;
});
或者使用对象分解-较短的语法
this.userService.getUserById(this.userId).subscribe((user: any) => {
const {salary} = user;
});
但是我需要的不是本地变量,而是全局变量,在angular的用户组件文件中
user.component.ts
我可以直接用攻击来解决这个问题
this.userService.getUserById(this.userId).subscribe((user: any) => {
this.salary = user.salary;
});
但是我找不到一种通过OBJECTT解构来实现这一点的方法
如果我这样做
const {this.salary} = user;
或
它不起作用
this.userService.getUserById(this.userId).subscribe(({salary}: any) => {
this.salary = salary;
});
或
破坏语法是从对象中获取属性。如果您确实需要,可以通过var
而不是const
来执行,但不建议这样做
您还可以制作如下内容:
const obj={
a:‘1’,
b:‘2’,
c:{
d:‘4’,
e:['5','6','7']
},
f:‘8’,
g:'9',
h:'10'
}
const{a,b:customName,c:{d,e:[first,…restArr]},…restObj}=obj;
//控制台日志(b)错误
//控制台日志(c)错误
//console.log(e)错误
//console.log(f)错误
//console.log(g)错误
//console.log(h)错误
log(a,customName,d,first);
console.log(restArr);
console.log(restObj)代码>没有办法用解构来完成。解构仅仅是对变量声明和赋值的语法上的甜言蜜语。你的第二套和第三套代码是不等价的,因为你在第二套中使用了this.user
。另外,要努力使你的代码可读性和可维护性,而不是聪明。
this.userService.getUserById(this.userId).subscribe(({salary}: any) => {
this.salary = salary;
});
this.userService.getUserById(this.userId).subscribe(({salary}: any) => this.salary = salary)