javascript - 创建具有对象属性的变量 - Angular
问题描述
我正在尝试创建一个变量来设置通过 get 方法获得的对象的属性之一。
当我在订阅中提供控制台时,我检索了数组的值,但是我很难(我是初学者)只设置该数组中对象的一个属性。
零件:
this.mainService.getGraph()
.subscribe(res => {
console.log(res)
this.name = res[''].map(res => res.name)
console.log(this.name)
控制台日志:
(5) […]
0: Object { name: "Carlos", lastname: "Moura", participation: 5 }
1: Object { name: "Fernanda", lastname: "Oliveira", participation: 15 }
2: Object { name: "Hugo", lastname: "Silva", participation: 20 }
3: Object { name: "Eliza", lastname: "Souza", participation: 20 }
4: Object { name: "Anderson", lastname: "Santos", participation: 40 }
length: 5
<prototype>: Array []
main.component.ts:26:6
ERROR TypeError: "res[''] is undefined"
ngOnInit main.component.ts:27
RxJS 13
Angular 8
解决方案
- 您正在
res
将传入的函数重新定义为map
. - 使用
name
to的复数names
,您需要一个字符串数组,因此复数更合适并传达字段包含的内容。 - 不要尝试访问 上不存在的字段或索引
res
,res['']
这是不正确的。 - 我将调用放入
ngOnInit
,它可能位于其他位置,但这允许我在其上方定义分配的变量成员。
names: string[];
ngOnInit() {
this.mainService.getGraph()
.subscribe(res => {
console.log(res);
this.names = res.map(_ => _.name);
console.log(this.names);
}
从评论:
... IDE 说“对象”类型上不存在属性“地图”。它只是一个错误吗
关于您的服务。确保返回类型上的签名正确。这是一个示例,您还可以定义一个接口并返回它而不是{name:string}
(但保留表示返回数组的 [])。
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export class MainService {
constructor(private readonly http: HttpClient){}
getGraph() : Observable<{name: string}[]> {
return this.http.get<{name: string}[]>('/some/url');
}
}
推荐阅读
- java - 避免在junit4中调用CommandLineRunner
- arrays - 什么时候数组 C-contiguous 和 F-contiguous 同时?
- jenkins - Scripted Pipeline 语法中并行内部的顺序阶段
- python - Python中多点下的面积积分
- r - 使用 mutate 将变量名称列表传递给自定义函数
- java - 为什么我的 Apache Ignite 持久存储仍处于锁定状态?
- python - 我无法在 pycharm 中导入 pygame
- elasticsearch - Logstash BeatsParser$InvalidFrameProtocolException
- java - 启动仪表 API 失败:Runner 意外退出
- javascript - 有没有办法使用“in”运算符排除某些元素?