What could be preventing the nesting of observables from functioning properly in Ionic-Angular?

Working with Observables has been an interesting experiment for me, but I'm facing an issue that I can't seem to resolve. While all the methods work perfectly fine when called outside the pipe, the problem arises when I nest them like this:

createUserWithEmailAndPassword(email, password): Observable<Session> {
    return from(this.firebaseAuth.createUserWithEmailAndPassword(email, password))
        .pipe(map(v => v.user as unknown as User),
            switchMap(this.userDatabase.createUser),
            map(this.userDatabase.createSession)
        );
}

This results in the following error being thrown:

ERROR TypeError: Cannot read property 'post' of undefined

at SwitchMapSubscriber.create (database-core.service.ts:57)
at SwitchMapSubscriber.createUser [as project] (database-user.service.ts:28)
at SwitchMapSubscriber._next (switchMap.js:30)
at SwitchMapSubscriber.next (Subscriber.js:49)
at MapSubscriber._next (map.js:35)
at MapSubscriber.next (Subscriber.js:49)
at subscribeToPromise.js:5
at ZoneDelegate.invoke (zone-evergreen.js:364)
at Object.onInvoke (core.js:27437)
at ZoneDelegate.invoke (zone-evergreen.js:363)

database-user:

createUser(user: User): Observable<User> {
    return super.create(this.DB_URL, user) //<--- line 28
        .pipe(map(v => v as unknown as User));
}

createSession(user: User): Session {
    const newSession: Session = {
        firstLogin: false,
        id: user.id
    };
    this.angularFirestore.collection('session').doc(user.uid).set(newSession)
        .catch(e => {
            throw new Error(e);
        });
    return newSession;
}

In database-core:

constructor(
    private globalService: GlobalService,
    protected httpClient: HttpClient
) {}
// (...)
protected create(url: string, data: any): Observable<JsonObject> {
    return this.httpClient.post<JsonObject>(url, data, this.globalService.getHttpOptions()) //<-- lines 57
        .pipe(catchError(DatabaseCoreService.handleError)); 
}

Subscribing to the observable:

createUser(email, password) {
    this.authService.createUserWithEmailAndPassword(email, password).subscribe();
}

App-Module:

@NgModule({
    declarations: [AppComponent],
    entryComponents: [],
    imports: [
        BrowserModule,
        IonicModule.forRoot(),
        AppRoutingModule,
        AngularFireModule.initializeApp(environment.firebaseConfig),
        HttpClientModule
    ],
    // (...)

Answer №1

The Issue

It appears that the problem lies within the super class where the http variable is showing up as undefined.

To see the error in action, you can visit the following link for the Error reproduction on stackblitz

In the example provided, there are two classes:

MySuperClass

export class MyClass {
  constructor(private htttp: HttpClient) {

  }
  create = user => this.htttp.post('some URL', user)

}

MyComponentClass

export class AppComponent extends MyClass implements OnInit {
  constructor(http: HttpClient) {
    super(http);
  }
  ngOnInit() {
    this.create({ name: "User" }).subscribe({
      next: console.log
    });
  }
}

The issue occurs in the provided code. This could be the problem you are encountering

Resolution

To address this issue, you need to define the value of http in the constructor of the super class

For a demonstration, you can check out this demo

In this demo, the http property is passed to the super class and initialized

MySuperClass

import { HttpClient } from "@angular/common/http";

export class MyClass {
  http: HttpClient;
  constructor(_htttp) {
    this.http = _htttp;
  }
  create = user => this.http.post("some URL", user);
}

MyComponentClass

export class AppComponent extends MyClass implements OnInit {
  constructor(http: HttpClient) {
    super(http);
  }

  ngOnInit() {
    this.create({ name: "User" }).subscribe({
      next: console.log
    });
  }
}

The above solution should resolve the issue. Double-check if this is the root cause in your code

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

Angular project set up with dynamic polyfill inclusion based on .browserslistrc configuration

In order to ensure that our software is compatible with older browser versions, we need to implement polyfills for Angular since it does not do this automatically. To achieve this, I am looking to add custom webpack configuration. Currently, I am working ...

What is the best way to implement a timeout and subsequently clear it in a React functional component?

Hello there, I am currently working on a functional component in ReactJS and I am facing an issue with implementing a timeout on mouse hover over a menu. The timeout functionality is working fine, but I am struggling to clear this timeout in another funct ...

Ionic-React - Triggering setState does not result in re-rendering

After invoking setMyState in a useEffect hook, I expect React to re-evaluate the logic to determine whether to render MyPage or IonSpinner. However, MyPage does not appear on the screen unless I switch to a different tab and return (using Ionic's IonT ...

Pattern matching for directory path excluding the filename

Looking for assistance with creating a JavaScript regex pattern to validate text input as folder paths only, excluding the filename. Can someone provide guidance on this? For example: folder1/folder2/folder3 => valid folder1/folder2/filename.txt1 =&g ...

Arranging Alphanumeric Characters in Angular in Ascending Order

I am trying to sort a list of characters first, followed by alphanumeric values. Here is what I have: [Austria , Germany , 123aed , 234eds] This is my current sorting attempt: obj.sort((a,b) => { if ( (isNaN(a.text) && isNaN(b.text)) || ...

To ensure the specificity selector for material UI in React, it is essential to include an empty CSS definition

The styling for the unselected toggle button is working smoothly. However, when you don't define an empty class selector, the style of the selected toggle button does not show: ./App.js import * as React from "react"; { render ...

Displaying [object Object] in Angular Material datatable

I am currently working on implementing a datatable component using Express and Firebase DB. Below is the service request data: getText() { return this.http.get<nomchamp[]>(this.url) .map(res => { console.log(res); return res }); ...

Encountering an issue with undefined error when performing two-way form binding with an object that implements an interface

I have defined an User interface: export interface User{ name:string; email:string: address:string; } After importing this interface on my Ionic page, I declared the following code in the class, just before the constructor: user:User; Later, in the ngO ...

Validate if the translation file exists in ngx-translate

Is there a way to determine if a translation file exists for the language obtained from navigator.language using ngx-translate? I am looking to implement something similar to: if( isLanguageAvailable(navigator.language)) { this.translate.use(navigator.l ...

Expanding the functionality of your Angular2 application on the fly post-Bootstrap

Angular 1 required all Services and Directives to be included in the Angular Application before the Bootstrap Phase. However, Angular 2 introduces a new feature called hierarchical Injectors. How do hierarchical Injectors allow for the addition of Servic ...

Pass a string with quotation marks to a component input in Angular 6

Need help with passing a string input to a component: @Component({ selector: 'abcComponent' template: ` <div> .... </div>` }) export class AbcComponent { @Input() text:string; } I am trying to send a strin ...

Exploring the Potential of Using ngIf-else Expressions in Angular 2

Here is a code snippet that I wrote: <tr *ngFor="let sample of data; let i = index" [attr.data-index]="i"> <ng-container *ngIf="sample.configuration_type == 1; then thenBlock; else elseBlock"></ng-container> <ng-template #t ...

Angular Binding issue - Unable to bind to 'ngModel' as it is not recognized as a valid property of 'input' element, despite the property being present

I have developed a component class like the one below and I am attempting to link the class fields to the template, but encountered the following error: ERROR in src/app/admin/projects/projects.component.html: 41:34 - error NG8002: Can't bind to &ap ...

When making a request from an Ionic client, Flask and Flask-SocketIO return a 404 error for the specified route

I am currently developing a real-time chatting and photo sharing application. For the server side, I am utilizing Flask to create RESTful web services, while for the client side on mobile, I am using the Ionic framework (AngularJS). One of the web service ...

The child components of the parent route in Angular 2 are organized as nested route components

Do nested route components act as children of the parent route component? Can they communicate by using an Output from a child route component to the parent route component? If not, what is the suggested approach in this scenario? Since components in rou ...

Resetting the timer of an observable in Angular 2

I have a unique service that automatically calls a method every 30 seconds. There is also a button that allows the user to reset the timer, preventing the method from being called for another 30 seconds. How can I make sure that the method does not get cal ...

How to avoid truncating class names in Ionic 4 production build

I have been working on an ionic 4 app and everything was going smoothly until I encountered an issue with class names being shortened to single alphabet names when making a Prod build with optimization set to true. Here is an example of the shortened clas ...

You were supposed to provide 2 arguments, but you only gave 1.ts(2554)

Hey everyone, I hope you're having a good morning. Apologies for the inconvenience, I've been practicing to improve my skills and encountered an issue while working on a login feature. I'm trying to connect it to an API but facing a strange ...

Custom hooks for Typescript and Javascript

As a beginner, I am currently working on refactoring JavaScript hooks into TypeScript. However, I am facing an issue where I cannot get the button onClick event to change state. Can anyone provide assistance with this? Here is the useToggler component: i ...

Tips for modifying a nested reactive form while ensuring validation is maintained?

When retrieving data from a service in the form of an array, one might wonder how to bind this data in a nested form if there are potentially endless entries in the array. The form is expected to be pre-filled with this data, including validation for each ...