首页 > 解决方案 > 创建具有对象属性的变量 - 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

标签: javascriptangulartypescript

解决方案


  1. 您正在res将传入的函数重新定义为map.
  2. 使用nameto的复数names,您需要一个字符串数组,因此复数更合适并传达字段包含的内容。
  3. 不要尝试访问 上不存在的字段或索引resres['']这是不正确的。
  4. 我将调用放入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');
  }
}

推荐阅读