Setting up a Variable with an Object Attribute in Angular

I am attempting to create a variable that will set a specific property of an object retrieved through the get method.

While using console.log in the subscribe function, I am able to retrieve the entire array value. However, as a beginner, I am struggling to modify only one property of the objects within 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

Answer №1

  1. You have redefined the variable res within your passed-in function to be named map.
  2. Change the singular form of name to names since you are working with a string array, and the plural form better describes the content of the field.
  3. Avoid trying to access a non-existent field or index in res, as in the case where you used res[''], which is incorrect syntax.
  4. I placed the function call inside ngOnInit. While it can be located elsewhere, this placement 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);
}

In response to comments:

The IDE is indicating that property 'map' does not exist on type 'Object'. Is this possibly a bug?

Regarding your service, ensure the signature for the return type is correct. Below is an example. You could also create an interface and use that as the return type instead of just {name:string}, maintaining the [] to indicate 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');
  }
}

Answer №2

To retrieve the names from an array of objects, you can simply use res.map(res => res.name). Avoid using res[''].map(res => res.name). It seems like you are attempting to access a property with an empty string as the key within your object, which does not exist.

Answer №3

If you wish to perform this action directly within the http get Method

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

Alternatively, if you only need to retrieve a single property from the response

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I keep receiving an error in Angular JS but I'm unsure of the reason

I've been working on AngularJS and created a basic module and controller. I'm attempting to show the data of an element inside the controller on the HTML view page, but all I see is {{student.name}} and I'm receiving an error message that sa ...

Utilize fetch API in React to streamline API responses by filtering out specific fields

I have received an API response with various fields, but I only need to extract the description and placeLocation. results: [{placeId: "BHLLC", placeLocation: "BUFR", locationType: "BUFR",…},…] 0: {placeId: "BHLL ...

Best practices for customizing Material UI v5 Switch using Theme

I've successfully implemented a Material Switch based on my design by creating a custom component and styling it using the styled and sx prop. However, I'm interested in figuring out how to achieve the same result within the theme itself so that ...

Storing information from a signup form using Angular

Can you help with my registration form? <div class="form-group"> <label for="email" class="col-sm-3 control-label">Email Address</label> <div class="col-sm-9"> <input type="email" id="email" placeholder="Enter your ...

Guide on how to switch a class on the body using React's onClick event

There's a button in my code that triggers the display of a modal-like div element. When this button is clicked, I aim to apply a class to the body element; then when the close button is clicked, I'll remove this class. I'm looking for guid ...

Having trouble with the installation of Parcel bundler via npm

Issue encountered while trying to install Parcel bundler for my React project using npm package manager. The terminal displayed a warning/error message during the command npm i parcel-bundler: npm WARN deprecated [email protected]: core-js@<3 is ...

Avoid the import of @types definition without exports in TypeScript to prevent the error TS2306 (not a module)

I have spent a considerable amount of time trying to load a NodeJS library that has what I believe is a faulty type definition in the @types repository. The library in question is geolib and its types can be found in @types/geolib Although I am aware tha ...

Nightwatch execute() function not technique following anticipate

After reviewing the documentation, I am confident that this code should work correctly. However, I am encountering an issue where something needs to run once the expect has finished, but it doesn't seem to be functioning as expected. Functioning Code ...

Updating the index page with AJAX in Rails 4: Step-by-step guide

It's surprising that I haven't found answers to my specific questions despite searching extensively. I have an Expenses page where I want to display all expenses for a given month in a table. Currently, I achieve this by adding month and year par ...

Alter the language settings of the Datepicker feature in Material Angular 4

Need help changing the language of Datepicker in Material Angular. Struggling to locate this information in the Angular material 2 documentation. Check out this plunkr https://plnkr.co/edit/unzlijtsHf3CPW4oL7bl?p=preview <md-input-container> < ...

Add the AJAX response to the dropdown menu options

Currently in my project, I am utilizing Laravel as a backend. The scenario is such that once the corresponding page loads, it triggers an ajax request to fetch vehicle data which consists of vehicle model and plate number properties. My aim is to display t ...

Visual Studio Code continues to compile code automatically without requiring me to save any changes

Question: VSC triggers compilation even without any file changes in Angular(6) project ng serve It's frustrating when Visual Studio Code starts compiling repeatedly, even when no changes have been made. How can I prevent this from happening? I&apos ...

Using AngularJS to Dynamically Set the Default Selection in a SELECT Element

In my code using JADE syntax, I have the following structure: select(ng-model="eventTypeUI") option(ng-repeat="c in eventUI", ng-value='c.value', ng-disabled='selectEventCanNotBeUsed(c.value)') {{c.name}} ...

Utilizing a combination of MVC, jQuery, and Ajax to ensure that JavaScript is fully loaded before proceeding

Utilizing ASP.NET MVC and jQuery, I am loading a PartialView via Ajax which has its own accompanying JavaScript file. Upon successful retrieval of the html content, it is inserted into the DOM. However, there can be a delay between the insertion and the ex ...

When using Angular 2 formControl, manually changing the value may not be detected by the form

Having a simple form (as shown below), I am encountering an issue: Manually entering input value causes form.controls['myValue'].value to change If #myInput value is changed programmatically, the form completely ignores that change What could ...

Error: Papa is not defined. The file was loaded from the CDN in the header section

I have integrated the cdn hosted lib for PapaParse in my HTML header. However, when I execute my JavaScript file and it reaches the function where I call Papa.unparse(data); It throws an error stating that Papa is undefined. This has left me puzzled as I h ...

Outputting data to a WriteStream within an Event Listener

My current issue involves an EventEmitter object set up to listen for events and write information to a file when the event is emitted. Using fs.createWriteStream(path, { flags: 'a'});, I have opened a FileStream. However, emitting events quickly ...

Strategies for displaying error messages in case of zero search results

I am currently developing a note-taking application and facing an issue with displaying error messages. The error message is being shown even when there are no search results, which is not the intended behavior. Can someone help me identify what I am doing ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...

Is there a way to invoke a class method from the HTML that is specified within its constructor function?

class Welcome { constructor() { this.handlePress = this.handlePress.bind(this); this.htmlContent = `<a onclick="this.handlePress">Link</a>`; } handlePress(e) { console.log('planet'); } } The HTML structure appears ...