In Angular 11, the error message "Type 'Object' cannot be assigned to type 'NgIterable<any> | null | undefined'" is appearing

Struggling to grasp the concepts of Angular and TypeScript for the first time, particularly puzzled by why this code snippet is not considered valid!

http.service.ts

export class HttpService {


  constructor(private http: HttpClient) { }

  getBeer() {
    return this.http.get('https://api.openbrewerydb.org/breweries')
  }
}

The API returns an object.

The component it's being used in: 


export class ListComponent implements OnInit {

  brews: Object;

  constructor(private _http: HttpService) { }

  ngOnInit() {
    this._http.getBeer().subscribe(data => {
      this.brews = data
      console.log(this.brews);
    }
  )
  }

}

An error arises with the line:

brews: Object;

The error message states:

Error TS2322: Type 'Object' is not assignable to type 'NgIterable | null | undefined'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?

I have attempted:

brews: any;

and

brews: Object[] = [];

However, neither solution seems to resolve the issue.

Could someone elucidate on where my mistake lies?

Given that the API returns an object, why am I unable to simply use:

brews: Object; 

The template it's intended for:

<h1>Breweries</h1>

<ul *ngIf="brews">
  <li *ngFor="let brew of brews">
    <p class="name">{{ brew.name }}</p>
    <p class="country">{{ brew.country }}</p>
    <a class="site" href="{{ brew.website_url }}">site</a>
  </li>
</ul>

Answer №1

If you are considering creating a custom type based on your `data`, that can be a great idea. However, if you prefer to use an anonymous type, you may find it helpful to utilize the `any[]` type to address the issue:

brews: any[];

You can also make use of generic methods in the http client by specifying `get`:

this._http.get<any[]>('https://api.openbrewerydb.org/breweries').subscribe(data => {
      this.brews = data 
      console.log(this.brews);
    })

Alternatively, you could try something along these lines:

this._http.get('https://api.openbrewerydb.org/breweries').subscribe(data => {
          this.brews = data as any[]
          console.log(this.brews);
    })

For a working example, check out this sample: StackBlitz

Answer №2

Avoid using generic names like 'httpservice' for your service as it can cause issues down the line.

Instead, consider utilizing a behavior subject to share objects as observables across all components.

Service

export class BeerService {
    private beer = new BehaviorSubject<any>({});
        public beer$ = this.beer.asObservable();
      
        getBeer(){
          this.http.get('https://api.openbrewerydb.org/breweries').pipe(map((res) => (res = res))).subscribe((sub) => {
            sub = sub;
            // set beer object next
            this.beer.next(sub)
            // , take(2)
             })
        }
      

In your component

  constructor(beer:BeerService) {}
  ngOnInit(){
       this.beer.beer$.subscribe((beer)=>{ 
      this.beer = beer})
  }

Learn more about behavior subjects here.

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

"Utilizing Angular's dynamic variable feature to apply ngClass dynamically

Looking for guidance on Angular - color change on button click. The loop binding is functioning well with dynamic variable display in an outer element like {{'profile3.q2_' + (i+1) | translate}}, but facing issues with [ngClass] variable binding ...

The IDE is able to detect interface extensions in d.ts files, but TypeScript is not recognizing them

When developing in ES6 style module inclusion within WebStorm, I encountered an issue with my Express app and a custom d.ts file. The d.ts file contains middleware that alters objects, and the structure looks like this: declare module Express { export ...

The Angular2 app and NodeJs in the Docker container are unresponsive

After creating a new Angular2 app using angular-cli and running it in Docker, I encountered an issue where I could not connect to it from localhost. First, I initialized the app on my local machine: ng new project && cd project && "put m ...

I am experiencing difficulties in assigning values to a formArray

I am struggling to update values in an array form, as I am facing challenges setting new values. Although I attempted to set values using patch value, my attempts were unsuccessful. // Component.ts this.packageForm = this.formBuilder.group({ title: [&a ...

Angular allows for the use of the ngIf condition within nested loops to control the display of

I'm currently working on implementing a navigation side menu using Angular with 3 levels of submenus. Below is the code I have tried: <ul class="nav metismenu" id="side-menu" *ngIf="menulist.length != 0"> <li *ngFor="let menu1 of menuli ...

"Exploring Angular 9: A guide to retrieving form data with an array of objects [Revised as of July 29th, 2020

I am encountering an issue with my Angular 9 form code. I am getting the error "ERROR TypeError: Cannot read property 'mobile_number' of undefined" and I need help in resolving this problem. <form (ngSubmit)="processForm()"> & ...

Utilize the RRule library in JavaScript by incorporating the rrule.min.js script

I am having trouble integrating the library https://github.com/jakubroztocil/rrule into my website. Whenever I try to do so, I encounter the error: Uncaught SyntaxError: Unexpected token { I have attempted the following: <!DOCTYPE html> <html ...

Issue encountered while generating dynamic Routes using the map function

When attempting to dynamically use Route from an array, I encounter an error. Warning: Incorrect casing is being used. Use PascalCase for React components, or lowercase for HTML elements. The elements I am utilizing are as follows: const steps = [ { ...

What could be the reason for the custom component app-transition-group and app-transition-group-item not functioning properly in Angular 8, even though it was working fine

I developed a unique Angular8 custom component that rearranges list items. However, I keep encountering the following error: Can't bind to 'app-transition-group' since it isn't a known property of 'ul'. Do you have any sugge ...

There is no overload that matches this call in Next.js/Typescript

I encountered a type error stating that no overload matches this call. Overload 1 of 3, '(props: PolymorphicComponentProps<"web", FastOmit<Omit<AnchorHTMLAttributes, keyof InternalLinkProps> & InternalLinkProps & { ...; ...

How to dynamically load a component within a class-based Vue component

I am facing an issue with loading two components dynamically using an object map. Info (options-based) SearchBar (class-based) While it works for the options-based component, I encounter an error stating _currentTab is undefined when trying to load a si ...

implementation of a grid tile in an Angular component

Here's what I am attempting to accomplish: <md-grid-list cols="3"> <product *ngFor="let product of products" [product]="product"></product> </md-grid-list> The product component includes a md-grid-tile. The issue: The ...

Issue with Material UI grid not rendering properly in TypeScript environment

I've been trying to replicate a grid from material-ui using React and Typescript. You can see a live demo here. I modified the example to work with Typescript, so my demo.tsx file looks like this: Code goes here... If you check out the live demo, y ...

What is the process for generating flexible paths (URL strings) in angular applications?

Within my <app-parent> component, I have multiple buttons that each open a new floating panel on top of the parent. These floating panels also contain buttons that trigger the opening of additional floating panels, creating a stacking effect. My go ...

How can I use Typescript to define a function that accepts a particular string as an argument and returns another specific string?

I've been working on this code snippet: const Locales = { en_gb: 'en-gb', en_us: 'en-us', } as const type ApiLocales = typeof Locales[keyof typeof Locales] type DatabaseLocales = keyof typeof Locales function databaseLanguage ...

Removing an image from the files array in Angular 4: A step-by-step guide

I have recently started working with typescript and I am facing a challenge. I need to remove a specific image from the selected image files array before sending it to an API. app.component.html <div class="row"> <div class="col-sm-4" *ngFor ...

Adjusting the width of row items in Angular by modifying the CSS styles

I am envisioning a horizontal bar with items that are all the same width and evenly spaced apart. They can expand vertically as needed. Check out the updated version here on StackBlitz Issue: I am struggling to automatically set the width of the row elem ...

Navigating with Angular 6 using routerlink in a child module with router-outlet specified in the parent component (app.component

I'm currently working with the RouterModule and encountering an issue with the routerLinks. The problem I am facing is that the routerLinks are not functioning properly (the anchor tags are not clickable). This issue arises because they are located w ...

The functionality of allowEmpty : true in gulp 4.0 does not seem to be effective when dealing with

gulp.task("f1", () => { gulp.src([], {"allowEmpty": true}) .pipe(gulp.dest(location)); }) An error message pops up saying "Invalid glob argument:" when the code above is used. gulp.task("f1", () => { gulp.sr ...

What steps should be followed to implement ng-zorro-antd?

I'm currently in the process of developing an Angular project with ng-zorro. I've followed these steps: npm install --location=global @angular/cli ng new ng-zorro-demo This Angular project includes routing. cd ng-zorro-demo/ ng add ng-zorro-antd ...