Unable to modify array in Angular 2 as it is either a constant or a read-only property

I am attempting to send a GET request to my backend API that will return an array of objects. The code I am using is as follows:

small.component.ts (when the function openDepositModal() is called, it triggers the function getUserInventory() from auth.service.ts, which then sends a GET request to the backend API and retrieves an array of objects.)

[...]

export class Item {
    id: String;
    name: String;
    img: String;
    value: String;
}

const items: Item[] = [];

[...]

openDepositModal() {
    if (!items) {
        this.authService.getUserInventory().subscribe(data => {
            items = data; <-- ERROR OCCURS HERE
        });
    }
}

auth.service.ts

[...]

getUserInventory() {
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', 'JWT ' + this.authToken);
    headers.append('Content-Type', 'application/json');
    return this.http.get('http://localhost:3000/api/user/inventory', { headers: headers })
    .map(res => res.json());
}

[...]

While working inside small.component.ts, I am trying to populate the "items" array with the data retrieved from the service. However, I encounter the error "cannot assign to array because it is a constant or a read-only property". Can someone please help me fix this issue in my code? Thank you. :-)

Answer №1

opt for let over const

for example: let items: Item[] = [];

const declarations are similar to let declarations, but unlike the latter, their value cannot be altered once set. In essence, they follow the same scoping rules as let, but you aren't allowed to reassign them.

let vs. const (documentation)

Given that there are two types of declarations with comparable scoping semantics, it's reasonable to wonder which one is preferable. The answer to this broad question ultimately depends on the context.

Following the principle of least privilege, all declarations that won't be modified should use const. The idea behind this is that if a variable doesn't require any changes, others working on the same code shouldn't automatically have the ability to alter it. They need to carefully consider if reassigning the variable is truly necessary. Utilizing const also enhances predictability in code by facilitating a clearer understanding of data flow.

However, some might argue that using let instead of var is more concise and readable. As a result, many users may prefer its brevity. This handbook primarily employs let declarations for this reason.

Answer №2

Change the mistake to this.items = data;

Answer №3

The reason is due to the constant declaration. To fix this, declare it as a property within your class so that you can assign values to it.

export class SmallComponent{
private items: Item[] = [];

[...]

openDepositModal(){
    if(!items){
        this.authService.getUserInventory().subscribe(data => {
            this.items = data; <-- This line here
        });
    }
}

If the variables are outside of the component class, simply change const to let

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

Do mousemove events become inactive when an element is being dragged?

My goal is to move an element based on mousemove events triggered by the document while the element is dragged using HTML5 drag and drop. I have added a mousemove listener to the document within a parent element that normally fires whenever I move my mouse ...

picker elementClass()

I encountered an issue while using the datepicker from Material UI. The datepicker has a method called dateClass: dateClass() { return (date: Date): MatCalendarCellCssClasses => { const unvailableArray = this.shareDate.unavailableDates; ...

Inspect Element: JSON data is being displayed rather than the expected HTML source code

When inspecting the page source, I noticed that instead of the HTML page, the JSON response (which is essentially the table data) is being displayed. Initially, I was trying to find a way to retrieve the JSON response while still rendering the HTML page. T ...

Ways to prevent the repetition of keys associated with values

I am currently dealing with an array called serialNumbers, which can have different structures. For example: lot: 1 Serial: 2 lot: 1 Serial: 3 lot: 1 Serial: 4 ...or it could look like this: lot: 1 Serial: 5 lot: 1 Serial: 9 lot: 8 Serial: 2 lot: ...

Please anticipate the completion of data loading

I need help adding a custom tweet button to my Angular application. Below is the code I am using: HTML: <a href="" class="retweet" retweet target="_blank" data-info="{{ data.name }}"> Tweet </a> JS: myApp.directive('retweet', ...

Unit testing Angular Primeng confirmation service can help ensure its functionality is working

In the component, I have a canDeactivate function set up as shown below. canDeactivate() { return new Promise(resolve => { if(this.close){ this.confirmationService.confirm({ message: 'Please close', header: 'Warning', ...

Transferring Information from the Initial XML Transmission to Following Pages

`I am currently dealing with an API that provides an XML response once a request is made. For instance, let's consider the following simplified example: <buildings> <building attr1="foo" attr2="bar"> <uri>http://blah.com&l ...

Sending information into MySQL using NodeJS with the help of Postman

As a newcomer in the field, I am exploring how to combine MySQL with nodeJS for integrating projects into WordPress. app.post('/users/add', (req, res) => { id = req.body.id, firstname = req.body.firstname, surname = req.body.surname ...

Repetition of Angular 4 component in routing for a specific path

Encountering an unusual issue where a specific route causes the component to be duplicated in the DOM when directly launched, but functions correctly when navigated from the main page. The problematic route is contact, utilizing the ContactComponent. You ...

Customizing exception handling in Ionic2 app

I have been working on an Ionic v2 App and trying to incorporate the ExceptionHandler from angular2. With Ionic2 not requiring the developer to explicitly call bootstrap, it appears challenging to implement this feature at the moment. Has anyone successfu ...

Using jQuery to access the data attribute values

Within my HTML code, there is a span element: <span class="field" data-fullText="This is a span element">This is a</span> I am trying to access the data-fullText attribute. I attempted two different methods, but unfortunately, they both retur ...

What could be causing Loudev jQuery multiselect to generate duplicates?

The concept involves allowing users to select a main bank branch via a search textbox that triggers a jQuery AJAX request. If the user wishes to add more branches, they can use a multiselect functionality provided later in the form for selecting one or mul ...

Utilizing the map function on an object that includes several arrays

I have a situation where my props object contains both a user comment array and a userId array. Initially, I only had the user comment array, which allowed me to style each comment individually using the map function. Now that there are two arrays inside m ...

How to Remove onFocus Warning in React TypeScript with Clear Input Type="number" and Start without a Default Value

Is there a way to either clear an HTML input field of a previous set number when onFocus is triggered or start with an empty field? When salary: null is set in the constructor, a warning appears on page load: Warning: The value prop on input should not ...

Interacting between host and remote in microfrontend communication

In my microfrontend application utilizing module federation, I am facing the challenge of establishing communication between the shell and remote components. When the remote component communicates with the shell using CustomEvent, everything works smooth ...

What is the best way to conceal a row when a particular field is devoid of content?

Is it possible to hide an entire table row if a field is empty? For example: https://i.sstatic.net/tMW7L.png If a certain field is empty, I want the entire row to be hidden, either using JavaScript or jQuery. I have tried some methods but none of them fu ...

Show information on the user interface by retrieving data from the backend

I'm facing an issue where I am unable to display a string on the client-side even though I fetch the data from the server-side successfully. When I log the variable directly in the js file, the server prints the string as expected. However, there seem ...

Unable to perform updates for personalized fonts

I've been trying to incorporate custom fonts into my website, but I seem to be facing difficulties in actually implementing them. Could someone please let me know if I am doing it correctly? .pattern{ background:rgba(0,0,0,.5) url(../images/pattern ...

Instructions for creating a JavaScript click function that iterates through all records, not just the initial record

Although I'm new to web development and still learning the basics of html, javascript, etc., I have a problem that seems quite simple. The challenge lies in understanding javascript functions, which I find particularly tough to grasp. Here's what ...

Do i++ and ++i function differently in a JavaScript for loop?

When it comes to C++, many argue that ++i is better than i++. ++i; // Fetch i, increment it, and return it i++; // Fetch i, copy it, increment i, return copy If you're interested, there's a similar discussion on Stack Overflow about C++. N ...