Felipe Noka
Felipe Noka

Reputation: 107

Create a Variable with an Object Property - Angular

I'm trying to create a variable to set one of the properties of an object obtained by the get method.

When I give console in subscribe I retrieve the value of the array, but I'm having difficulty (i'm beginner) to set only one of the properties of the objects in that array.

Component:

this.mainService.getGraph()
    .subscribe(res => {
      console.log(res) 
      this.name = res[''].map(res => res.name)
      console.log(this.name)

Console.log:

(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

Upvotes: 2

Views: 9577

Answers (3)

Igor
Igor

Reputation: 62213

  1. You are redefining res in your passed in function to map.
  2. Use a plural of name to names, you want a string array so the plural is more appropriate and conveys what the field contains.
  3. Do not try to access a non existent field or index on res, you had res[''] which is not correct.
  4. I put the call in ngOnInit, it might be located elsewhere but this allowed me to define the assigned variable member above it.
names: string[];

ngOnInit() {
    this.mainService.getGraph()
      .subscribe(res => {
        console.log(res);
        this.names = res.map(_ => _.name);
        console.log(this.names);
}

From the comments:

...the IDE says property 'map' doesnt exist on type 'Object'. would it just be a bug

About your service. Make sure the signature is correct on the return type. Here is an example, you can also define an interface and return that instead of {name:string} (but keep the [] which denotes there is an array being returned).

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');
  }
}

Upvotes: 2

Abel Valdez
Abel Valdez

Reputation: 2408

You can do it directly in the http get Method

this.http.get(url).pipe(
 map(res => {
   res['newProperty'] = 'value';
   return res;
 })
);

Even if you want just call back just one property

this.http.get(url).pipe(
     map(res => {       
       return res.name;
     })
    );

Upvotes: 0

Andrei
Andrei

Reputation: 12021

Just use res.map(res => res.name). instead of res[''].map(res => res.name). In your case you are trying to access property with key equal to empty string inside of your object, and it doesn't exist

Upvotes: 0

Related Questions