The firebase-generated observable is causing the notorious differ error as it is not iterable

Hey there, I'm encountering an issue that's preventing the route from rendering correctly. I initially thought that unwrapping an observable into an iterable using the async pipe would solve it, but this error indicates otherwise. Sometimes observables can be confusing. What do you think is causing the problem? Should I map this to an array before proceeding?

Error:

 MyOrdersComponent.html:5 ERROR Error: Cannot find a differ supporting object 'https://oshop-c71db.firebaseio.com/orders' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
        at NgForOf.ngOnChanges (common.js:2570)
        at checkAndUpdateDirectiveInline (core.js:12348)
        at checkAndUpdateNodeInline (core.js:13876)
        at checkAndUpdateNode (core.js:13819)
        at debugCheckAndUpdateNode (core.js:14712)
        at debugCheckDirectivesFn (core.js:14653)
        at Object.eval [as updateDirectives] (MyOrdersComponent.html:5)
        at Object.debugUpdateDirectives [as updateDirectives] (core.js:14638)
        at checkAndUpdateView (core.js:13785)
        at callViewAction (core.js:14136)

Template:

<h1>My Orders</h1>

    <p *ngFor="let order of this.orders$ | async">{{ order.datePlaced | date}}</p>

    <p class="card-text">You currently have 0 orders placed.</p>

    <table class="table table-hover table-striped ">
        <thead>
            <tr>
                <th>Order Placed</th>
                <th>Total</th>
                <th>Ship To</th>
                <th>Order Number</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let order of this.orders$ | async">
                <td></td>
                <td>{{ order.datePlaced | date}}</td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
        </tbody>
    </table>

Component:

import { AuthService } from './../auth.service';
    import { OrderService } from './../order.service';
    import { Component, OnInit } from '@angular/core';
    import 'rxjs/add/operator/switchMap';

@Component({
    selector: 'app-my-orders',
    templateUrl: './my-orders.component.html',
    styleUrls: ['./my-orders.component.css']
})
export class MyOrdersComponent {
    orders$;

    constructor(
        private authService: AuthService,
        private orderService: OrderService) {

        this.orders$ = authService.user$.map(u => orderService.getOrdersByUser(u.uid));
        // console.log(this.orders$);
    }
}

Order Service:

 import { AngularFireDatabase } from 'angularfire2/database-deprecated';
    import { Injectable } from '@angular/core';
    import { CartService } from './cart.service';

    @Injectable()
    export class OrderService {
        constructor(
            private db: AngularFireDatabase,
            private cartService: CartService
        ) { }

        async placeOrder(order) {
            const result = await this.db.list('/orders').push(order);
            this.cartService.clearCart();
            return result;
        }

        getOrders() {
            return this.db.list('/orders');
        }

        // getOrdersByUser(userId: string) {
        //     return this.db.list('/orders').$ref.orderByChild('userId');
        // }
        // getOrdersByUser(userId: string) {
        //     return this.db.list('/orders'.
        //         ref => ref.orderByChild('userId').equalTo(userId));
        // }
        getOrdersByUser(userId: string) {
            return this.db.list('/orders').$ref.orderByChild('userId').equalTo(userId);

        }

    }

Answer №1

If you are working with a function named getOrdersByUserId, it indicates that you will likely be dealing with an

Observable<Observable<T>>
, an
Observable<Promise<T>>
, or an Observable<T[]>.

In this case, using flatMap instead of map would be the appropriate approach.

Alternatively, consider utilizing concatMap or switchMap as mentioned in the comments.

Keep in mind that flatMap is essentially the same as

mergeMap</code (or vice versa), so you may opt to use either interchangeably. However, for consistency sake, it is recommended to stick to using just one - either <code>mergeMap
or flatMap throughout your project, as there are already plenty of terms referring to these operations.

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

What was the process for implementing the lexer and parser?

My journey into the depths of programming languages led me to explore how TypeScript is implemented, prompting me to venture into its Github repository. Within the language's source code under /src/compiler, I stumbled upon intriguing files like scan ...

Angular input for date is showing wrong value due to timezone problem

My database stores dates in UTC format: this.eventItem.date: "2023-06-21T00:00:00.000Z" The input form field value is showing '2023-06-20' (incorrect day number), which seems to be a timezone issue. I am located in a region with a +3 o ...

How to Customize Bootstrap Colors Globally in Angular 4 Using Code

I am interested in developing a dynamic coloring system using Angular. I have set up a service with four predefined strings: success, info, warning, and danger, each assigned default color codes. My goal is to inject this service at the root of my applicat ...

Using Angular 5 to access a variable within a component while iterating through a loop

I am currently in the process of transferring code from an AngularJS component to an Angular 5 component. Within my code, I have stored an array of objects in a variable called productlist. In my previous controller, I initialized another empty array nam ...

The navigator.geolocation.watchPosition call did not return any available position information

I offer a service that monitors the position of devices: getLocation(opts): Observable<any> { return Observable.create(observer => { if (window.navigator && window.navigator.geolocation) { window.navigator.geolocat ...

Guide to successfully submitting an Angular form that includes a nested component

I have developed a custom dateTime component for my application. I am currently facing an issue where I need to integrate this component within a formGroup in a separate component. Despite several attempts, I am unable to display the data from the child fo ...

Error message: "Mismatched data types in Formik errors when utilizing TypeScript"

I have a customized input component for formik which includes an error label if one exists. When I print it like this: {errors[field.name]}, it works. However, {t(errors[field.name]?.toLocaleString())} does not work. import { FieldProps, FormikErrors } ...

Is the ng-selector in Angular2 not sorting items alphabetically as expected?

This code snippet demonstrates the use of ng-selector in an .html file <ng-selector name="company" [(ngModel)]="company_selected" [formControl]="loanApplyForm.controls['company']" ...

Having trouble with NPM build getting stuck in Azure DevOps

There seems to be a problem similar to the one discussed in this question: npm run build hangs indefinitely on azure. Our build process has been functioning smoothly for several months. However, we are currently facing an issue where npm build is failing ...

How can I add a JavaScript-created element into a Primeng TurboTable component?

I am in the process of replacing a custom-made table with PrimeNG's turbotable. The issue I'm facing is that when I try to insert buttons into the table that call specific JavaScript functions, they end up displaying as [object HTMLInputElement] ...

Tips for maintaining an open ng-multiselect-dropdown at all times

https://www.npmjs.com/package/ng-multiselect-dropdown I have integrated the ng multiselect dropdown in my Angular project and I am facing an issue where I want to keep it always open. I attempted using the defaultOpen option but it closes automatically. ...

Tips on clearing and updating the Edit Modal dialog popup form with fresh data

This code snippet represents my Edit button functionality. The issue I am facing is that I cannot populate my Form with the correct data from another component. Even when I click the (Edit) button, it retrieves different data but fails to update my form, ...

The scroll animation feature was not functioning properly in Next.js, however, it was working flawlessly in create react app

I recently transitioned a small project from Create React App (CRA) to Next.js. Everything is working as expected except for the scroll animations in Next.js, which are not functioning properly. There are no errors thrown; the animations simply do not occ ...

Having trouble getting my Angular project up and running - facing issues with dependency tree resolution (ERESOLVE)

Currently, I am in the process of following an Angular tutorial and I wanted to run a project created by the instructor. To achieve this, I referred to the steps outlined in the 'how-to-use' file: How to use Begin by running "npm install" within ...

I am curious if there is a feature in intro.js that allows for the highlighting of text or images to

I am having trouble getting intro.js to work with Ionic 4 as the highlighted text is not showing up view image here This is how I implemented the code in Angular 7: intro() { let intro = introJs.introJs(); intro.setOptions({ exitOnOverlayClick: false, ...

Guide on troubleshooting *.ts files in an ionic 2 project using Chrome's inspect devices feature

After successfully creating my Ionic 2 application for Android using the command "ionic build android", everything seems to be working fine. I have been debugging the app by using Chrome inspect devices, but now I am facing an issue. I am trying to debug ...

Never display mat-select panel when closed

In my current scenario, I am using the following template structure: <mat-select #select> <mat-option *ngFor="let option of optionsData"> {{ select.panelOpen ? option.viewValue : option.value }} </mat-option&g ...

When trying to upload a file with ng-upload in Angular, the error 'TypeError: Cannot read properties of undefined (reading 'memes')' is encountered

Struggling with an issue for quite some time now. Attempting to upload an image using ng-upload in angular, successfully saving the file in the database, but encountering a 'Cannot read properties of undefined' error once the upload queue is comp ...

The npm warning indicates that the file node_modules/.staging/typescript-8be04997/lib/zh-CN/diagnosticMessages.generated.json does not exist due to an ENOENT error

I am currently in the process of running npm install on a Linux machine where I do not have sudo access. Unfortunately, I have a machine-specific package.json and package-lock.json that cannot be changed. However, I encountered some errors during the insta ...

Module '. ' or its corresponding type declarations cannot be located

While working on my project with TypeScript and using Cheerio, I encountered an issue when trying to compile it with TSC. The compiler threw the following exception: error TS2307: Cannot find module '.' or its corresponding type declarations. 2 ...