Issue TS2322: The type 'Observable<any>' cannot be matched with type 'NgIterable<any> | null | undefined'

Encountering an error while attempting to fetch data from the API. See the error image here.


export class UserService {
baseurl: string = "https://jsonplaceholder.typicode.com/";
  constructor(private http: HttpClient) { }

listUsers(){
  //this.http.get(this.baseurl+ 'users').subscribe(responseData => console.log(responseData));
return this.http.get(this.baseurl + 'users');
}
}

list-users.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from 'src/app/services/user.service';
import { Observable } from 'rxjs';
@Component({
  selector: 'app-list-users',
  templateUrl: './list-users.component.html',
  styleUrls: ['./list-users.component.css']
})
export class ListUsersComponent implements OnInit {
   listUsers!: Observable<any>;
constructor(private userService: UserService){}
  ngOnInit(): void {
this.listUsers=this.userService.listUsers();
   
  }

list.users.component.html

<ul>
    <li *ngFor="let user of listUsers">
        {{ user.name }}
    </li>
</ul>

Facing an error while trying to retrieve data via the API.

Answer №1

The most recent update in Angular (version 14) requires a slight modification in the list-users.component.ts file.

    import { Component, OnInit } from '@angular/core';
    import { UserService } from 'src/app/services/user.service';
    import { Observable } from 'rxjs';
    @Component({
      selector: 'app-list-users',
      templateUrl: './list-users.component.html',
      styleUrls: ['./list-users.component.css']
    })
    export class ListUsersComponent implements OnInit {
       listUsers: yourInterfaceName[]=[];
    constructor(private userService: UserService){}
      ngOnInit(): void {
    this.userService.listUsers().subscribe((res)=>{
      this.listUsers = res;
    }) 
  }

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

Issue with Mat-AutoComplete arising while utilizing a formArray

After adding a form array to account for multiple rows, I had to modify my definition from: shoppingCartList Observable<any[]>; to shoppingCartList: Observable<any[]>[] = [];. However, this change resulted in an error in my filter function whic ...

Troubleshooting Problem with Angular Material 2's Mat-Paginator [Length] Bug

Utilizing the mat-paginator component for a table, I am facing an issue where I am unable to dynamically set the length of the paginator based on the total number of results retrieved from an API call. Despite trying various methods like setting it in the ...

The ngx-translate library could not be located within Ionic Framework 6

Currently, I am looking to incorporate the ngx-translate Pipe for translating my Ionic application. In my app.module.ts file: export function createTranslateLoader(http: HttpClient): TranslateHttpLoader { return new TranslateHttpLoader(http, './ass ...

Angular - Implementing filter functionality for an array of objects based on multiple dropdown selections

I am currently working on filtering an array of objects based on four fields from a form. These four fields can be combined for more specific filtering. The four fields consist of two dropdowns with multiple selection options and two text boxes. Upon cli ...

Angular Material - Data Table Kit

Struggling with setting custom styling for a mat-table in Angular Material. I want to adjust the border radius of the table and change the spacing inside to "space-between". The design I'm aiming for is shown here: Design Any tips or suggestions woul ...

Using angular 7 to apply a dynamic CSS class on a span element

I want to dynamically change the CSS class of a span element in an ngx datatable based on the value. Here is my HTML code: <ngx-datatable #orderinvoice class="bootstrap" [rows]="invoiceSource" [headerHeight]="50" [footerHeight]="50" [rowHe ...

Error: Module not found - Unable to locate 'dropzone'

Since migrating from Angular 4.4 to Angular 8.0, I encountered the following issue: ERROR in ./src/attributes/import/import.component.ts Module not found: Error: Can't resolve 'dropzone' in 'C:....\src\attributes\imp ...

Navigating the complexities of transferring data between components

I recently started working with Angular 6 and encountered an issue while trying to share data in my project. Below is the code snippets: 1) Component Sidebar: selectedCategory(type:any) { this.loginService.categoryType = type; // need to pass this d ...

Show the Search Results from Angular 2 in a Separate Component

When I search, the names are displayed on a suggestion list without any issues because they are not in a separate component. Search HTML <input type="text" placeholder="Search" (keyup)="getSuggestion($event.target.value)"> <div class="suggest ...

Angular2 application encounters issue with target attribute being overlooked by Chrome

I am trying to implement a link in an iframe following the instructions on W3Schools: <iframe height="300px" width="100%" src="demo_iframe.htm" name="iframe_a"> </iframe> <p><a href="http://www.w3schools.com" target="iframe_a">W3S ...

Extract values from a deeply nested object while retaining the type information

How can I map all object values of the first obj while preserving the generic type for the Wrapped object? I attempted this using a mapped type, but encountered two issues: I'm struggling to represent a nested Object in the MapToWrappedType I can&ap ...

Encountering problem installing "kendo-angular-grid" via npm

I am currently working on a project that utilizes kendo. Here is the content of the package.json file: Package.json- { "name": "angular-2-webpack-starter", "version": "0.1.0", "description": "A starter kit for angular 2 and webpack", "scripts": { ...

Unable to use console log in shorthand arrow function while working with Typescript

When debugging an arrow function in JavaScript, you can write it like this: const sum = (a, b) => console.log(a, b) || a + b; This code will first log a and b to the console and then return the actual result of the function. However, when using TypeSc ...

Error message when running `ng serve` - tips for troubleshooting?

I recently retrieved an older angular project (about 6 months old) that I wanted to use as a template. However, when I attempt to run it, I encounter the errors mentioned below. After doing some research online and reading through a few links, I found sugg ...

Tips for importing a non-namespaced module TypeScript definition into my custom types

When working with my custom types, I want to utilize the GraphQLSchema from the graphql module. If I simply write: interface MyThing { schema: GraphQLSchema } It doesn't reference the actual GraphQLSchema definition from the module (it's just ...

The Angular component fails to load in the browser because of a problem with the Observable subscription

Whenever I try to execute the getCurrentSalahOrIqamah function in the ngOninit lifecycle hook of this component, my browser gets stuck and the component doesn't load properly. I've attempted using both lazyloaded and eager loaded components, but ...

Creating dynamic charts using Angular 7 with Chartjs and mapping JSON data

Struggling to map JSON Data for a Bar-Chart display. The desired final Array should be: [883, 5925, 17119, 27114, 2758]. Seems like the Array I'm trying to use for barChartData (dringlichkeitenValues[]) is empty. Apologies for my coding skills. Can so ...

What is the best method to condense an array or extract only the valid values?

Looking to find the total count of properties that are true from an array of objects? Here's an example: let data = [ { comment: true, attachment: true, actionPlan: true }, { whenValue: '', ...

Angular Test Error: Refactoring requires a source file to be present

Trying to execute the command ng test, I encountered an error message. How can this issue be resolved? I am unsure of its meaning. ERROR in Must have a source file to refactor. To eliminate this warning, use "ng config -g cli.warnings.versionMismatc ...

What is the most effective way to retrieve a specific type of sibling property in TypeScript?

Consider the code snippet below: const useExample = (options: { Component: React.ComponentType props: React.ComponentProps<typeof options.Component> }) => { return } const Foo = (props: {bar: string; baz: number}) => <></& ...