You cannot access the Angular httpClient object using string literals

I'm encountering an issue with a for loop in my component. It's giving me an error stating that the data isn't iterable, even though it's supposed to be an array. How can I resolve this problem?

this.httpService.getUser().subscribe((data: Task[]) => this.task = data);

However, when I try to implement the above code snippet, I get the following error message:

error: object access via string literals is disallowed

In my setup, I have an interface defined as follows:

Task.ts

export interface Task {
  taskCategory: string;
  taskTitle: string;
  taskDescription: string;
  taskCompleted: boolean;
}

Additionally, there is a task.json file structured like so:

{
  "todoList": [
    {
      "taskCategory": "frontend",
      "taskTitle": "fix a bug",
      "taskDescription": "we have a bug with drag and drop in todo table, fix it",
      "taskCompleted": false
    },
    {
      "taskCategory": "back-end",
      "taskTitle": "send data",
      "taskDescription": "send data from back-end",
      "taskCompleted": false
    }
  ]
}

The corresponding http.service.ts file looks like this:

@Injectable({
  providedIn: 'root'
}
)
export class HttpService {
  #url = '/assets/task.json';
  constructor(private http: HttpClient) { }

  getUser(): Observable<Task[]> {


    return this.http.get<Task[]>(this.#url);
  }
}

Lastly, there's a component with the following setup:

export class AppComponent implements OnInit {
  title = 'http';
  task: Task[] = [];
 
  constructor(private httpService: HttpService) { }
  user: User[] = [];
  ngOnInit() {
   
    this.httpService.getUser().subscribe((data: Task[]) => {
      for (let item of data) {
        this.task = [{
          taskCategory: item.taskCategory,
          taskCompleted: item.taskCompleted,
          taskDescription: item.taskDescription,
          taskTitle: item.taskTitle
        }]
      }
    });
  }


}

To display the data on the HTML page, I use the following code snippet:

<div *ngFor="let item of task; index as i">
  {{item.taskCategory}}
</div>

Answer №1

Back in the earlier editions of Angular, the process involved converting the response into JSON by executing:

http.get(url)
    .map( res => res.json() )
    .subscribe( data => ... )

But in more recent versions (specifically Angular 8+), it is necessary to specifically observe the data within the response if that is your sole requirement:

http.get(url, { observe : "response" })
    .subscribe( data => ... )

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

Achieving unique records in a *ngFor loop: best practices

Is there a way to extract only unique records from this array? Specifically, I am interested in obtaining unique {{ subitem.author }} values from this list of items. <div *ngFor="let item of items"> <ion-list *ngFor="let subitem of item.it ...

Convert numeric month to its 3-letter abbreviation

Receiving the date time value from the server and storing it in a variable named a1: let a1 = (new Date(estimatedServerTimeMs)); console.log of a1 Sun Apr 05 2020 11:36:56 GMT+0530 (India Standard Time) The date is converted to a simpler format such as ...

What is the best way to invoke a TypeScript function within a jQuery function?

Is it possible to invoke a TypeScript function within a jQuery function? If so, what is the correct approach? Here is an example of my component.ts file: getCalendar(){ calendarOptions:Object = { height: 'parent', fixedWeekCount : ...

Tips for managing an HTTP request queue on Android when dealing with large file uploads

Currently, I am developing an android application that can function both offline and online. One of the key features is the ability to upload picture, audio, and video files. However, in order to upload a media file, an active internet connection is requi ...

Encountering an issue with importing { Firebase } from '@firebase/app' within an Angular Ionic project

I have been following a tutorial on how to transform my Ionic Angular App into a PWA and integrate web push notifications. The tutorial can be found here. However, I encountered an issue when reaching this specific section of the tutorial: import {Injecta ...

What is the alternative method in Jest unit tests to mock a method called within the `created` Vue lifecycle hook without relying on the deprecated `methods` parameter in `shallowMount`

Please note that the "duplicate" question and answer do not address my specific issue. Please consider voting to reopen or providing an explanation for the closure in the comments. In my scenario, I have a created() hook that invokes the doSomething() met ...

Set identical values for multiple arrays within an object

Hey there, I am currently trying to set a single value across multiple dynamic arrays and nested arrays within a single object. Here is the object I am working with: object = { metaForm: [{ id: 1, text: 'abc', Additional ...

What is the process to verify a password?

Hey everyone! I've successfully implemented control forms in my login.component.ts for handling email and password input. Now, I want to add these controls to my register.component.ts as well. Specifically, how can I implement controls for the passwor ...

Utilizing Typescript to troubleshoot linting issues

After running the TypeScript linter, I received the following error message: Do not use Function as a type. The Function type accepts any function-like value, providing no type safety when calling the function. This lack of specificity can lead to common ...

How to retrieve the data from a PHP file using Angular 4 CLI?

Is there a way to retrieve the response from a PHP file using Angular 4? If the PHP file is placed in the assets folder, the GET request will identify the file and proceed to download its content. For example: headers: Headers ok: true status: 200 status ...

Utilizing Min and Max Validation in Angular 2 Template-Driven Forms

I attempted to incorporate min validation in a template form, but unfortunately it did not function as expected. Could someone provide guidance on how to properly use it in a template form? Thank you in advance for your assistance. <input type= ...

Validating Form Controls with Dynamic Names in Angular 5

Initially, I believed this task would be straightforward. The following snippet of HTML is functioning as anticipated: <label class="mb-0 form-label"> Doc Part </label> <input type="number" name="DocPart" #DocPart="ngModel" class="form- ...

Utilize TypeScript enum keys to generate a new enum efficiently

I am in need of two Typescript enums as shown below: export enum OrientationAsNumber { PORTRAIT, SQUARE, LANDSCAPE } export enum OrientationAsString { PORTRAIT = 'portrait', SQUARE = 'square', LANDSCAPE = 'landscape&ap ...

Ruby- efficiently remove a value from a sorted and unique array with a time complexity of O(log n)

I have a sorted array with unique values and no duplicates. While I am aware of the Array#binarysearch method for finding values in the array, I am wondering if there is a way to delete a value at O(log n) efficiency. How would I go about achieving this? ...

Creating a new array by combining data from two arrays: a step-by-step guide

Here is an array I have: response=[ { "mId": "4a993417-3dae-4a85-bb2e-c535d7fda6d7", "title": "test2", "score": "4", "id": "91ce873f- ...

Exploring the Concept of Template Element Recursion in Angular JS 2

In my Angular 2 project, I encountered a situation where I needed to iterate through ngFor based on child elements. My component should be able to render a list based on the input provided. Here is an example of the data structure: [ { name: 'ABC ...

"Enhancing the appearance of mat-sidenav elements in Angular Material 7 with customized

Our previous dom-structure before upgrading to Angular 7 and Material 7 looked like this: <mat-sidenav-container> <mat-sidenav #sidenav mode="side" [opened]="sideNavOpen"> <ul> <li> <a mat-icon-button color ...

Receiving a collection of MultipartFile objects from Angular

I've been facing difficulties with sending multiple files from my Angular front-end to my Spring Boot back-end. I've searched through various forums and websites, but haven't been able to find a solution. Here's the code snippet in ques ...

Arranging an array according to the key values in a different array

I am facing a challenge with two arrays: $array_sorter = [ 'XXS' => 1, 'XS' => 2, 'S' => 3, 'M' => 4, ...

Excel - Fetch data from an array

Within my company, there are specific excel functions that produce a large array containing over 2000 rows and multiple columns. Here is a generic example: {=FunctionThatReturnArray(param1)} where param1 represents the date I am looking to extract the ...