The abstract class is experiencing an undefined imported service issue

After creating an abstract class called Collection, which relies on a service known as Database to set up collections within a database, I found that all subclasses of Collection require the same database initialization process. This leads me to believe that Collection serves as a base class for these instances.

However, when looking at the subclass FooCollection, I encountered an issue where the imported service Database is somehow undefined in its constructor. It's puzzling because the constructor of the Database service is definitely executed before the Foobar constructor.

What could be causing the imported service to be undefined in FooCollection? Is it a misconception on my part or possibly related to how classes are loaded?

Collection.ts:

import { Database } from '../providers/database';
import {Injectable} from "@angular/core";

@Injectable()
export abstract class Collection {

  public name : string;

  constructor(public db : Database) {
     // db is undefined here -> crash
     db.doSomething();
  }
}

Database.ts:

import {Injectable} from '@angular/core';
import 'rxjs/add/operator/map';

@Injectable()
export class Database {

  private _db: any = null;

  constructor() {
    console.log('Hello Database Provider');
  }

  public doSomething(): void {
      console.log("doSomething");
  }
}

FooCollection.ts:

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Collection} from '../classes/collection';


@Injectable()
export class FooCollection extends Collection{
}

app.module.ts:

import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { Start } from '../pages/page/start';
import { Database } from '../providers/database';
import { FooCollection } from "../providers/foocollection";

@NgModule({
  declarations: [
    MyApp,
    Start
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    Start
  ],
  providers: [
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    Database,
    FooCollection
   ]
})
export class AppModule {}

Start.ts:

import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

import { FooCollection } from '../../providers/foocollection';

@Component({
  selector: 'page-start',
  templateUrl: 'start.html'
})
export class Start{
  constructor(public navCtrl: NavController, public f: FooCollection ) {
  }
}

EDIT:

I made a discovery that explicitly importing Database again in FooCollection resolves the issue:

import { Injectable } from '@angular/core';
import { Database } from './database';
import 'rxjs/add/operator/map';
import { Store } from '../classes/store';

@Injectable()
export class Calls extends Store {
  constructor(public db : Database) {
    super(db);
  }
}

This brings up the question of how imports are managed in subclasses of abstract classes.

Answer №1

It's important to include the database in the module where it is being used. Additionally, make sure to provide the Foo collection as well, as demonstrated in this sample code.

@NgModule({
  providers: [Database, FooCollection]

Answer №2

Unfortunately, I am unable to leave a comment at the moment, so I am sharing my thoughts here instead. Recently, I updated my application from version 2.4.5 to 4.0.0, only to encounter the same issue once again! I have an abstract service (a) that injects a cache service (as protected), and then extend that service (b) to introduce additional functionality.

Subsequently, the extended service (b) is utilized in a resolver.

The problem arises when the resolver attempts to call a method in service B that relies on one of the injected services in A. Surprisingly, these injected services are now deemed undefined. After double-checking, I confirmed that everything functions flawlessly in the previous version 2.4.5.

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

Creating a Precise Millisecond Countdown Timer using Angular 4 in Javascript

I'm currently facing a challenge in Angular 4 as I attempt to develop a countdown timer that accurately displays milliseconds once the timer falls below 1 minute (59 seconds or less) for a sporting event clock. My issue lies with the setInterval funct ...

Typing Redux Thunk with middleware in TypeScript: A comprehensive guide

I recently integrated Redux into my SPFx webpart (using TypeScript), and everything seems to be working fine. However, I'm struggling with typing the thunk functions and could use some guidance on how to properly type them. Here's an example of ...

Disabling dates in Kendo Date Time Picker (Angular): An easy guide

<input id="startDate" kendo-date-time-picker k-ng-model="vm.startDate" k-on-change="vm.updateStartDate()" required /> Can someone please explain how to incorporate disabled dates into this date picker without utilizi ...

The highcharts-angular version of the stock-tools-gui demo is lacking a graphical user interface (GUI)

Attempting to create an Angular version of this impressive demo: https://www.highcharts.com/stock/demo/stock-tools-gui . Utilizing the highcharts-angular wrapper in this project: https://codesandbox.io/s/pjkqwwmkr7 - everything is functional except for t ...

Angular2: The NgFor directive is designed to work with Iterables like Arrays for data binding

I'm currently working on a university project to develop a web application consisting of a Web API and a Frontend that interacts with the API. The specific focus of this project is a recipe website. Although I have limited experience with technologies ...

Unfortunately, my capabilities do not allow me to execute the command 'ng build --configuration production

This is the issue that I am facing and need assistance: Error: src/app/app.component.html:1:1 - error NG8001: 'fuse-progress-bar' is not recognized as a valid element: If 'fuse-progress-bar' is an Angular component, please ensure that ...

How do I specify the return type of a function in Typescript that can return more than one type?

I am facing a situation where I have a method called getFilters that retrieves various types of values. getFilters(): IListFilteringType {...} type IListFilteringTypeMultiSelect = (string | number)[]; type IListFilteringType = boolean | string | number | ...

Combining Promises in Typescript to create a single Promise

Is there a way for me to return the temp_data object filled with data after using .map? Currently, it always returns undefined because I initialize temp_data as an empty object. But if I don't do this, I can't use LooseObject. Can anyone suggest ...

Using React to render an icon based on the value of props

I am working on a vacation project using React (TS), NodeJS, and mySQL. I am attempting to implement save and like icons with Material UI based on certain props conditions. The icons are located within the div className "MenuContent". How can I create a fu ...

What is the best way to share a configuration value retrieved from the back end across all components of an Angular 6 application?

In the Web API's Web.config file, I have defined configurations like MAX_FILE_SIZE and others. I want to retrieve these configurations from the backend and make them available to all Angular 6 components globally. Could someone suggest the most effect ...

The data type 'Event' cannot be assigned to the data type 'string' in this context

Recently diving into Angular, I came across a stumbling block while working through the hero tutorial. The error message that popped up was: Type 'Event' is not assignable to type 'string' You can see the error replicated here. ...

Angular 2 Rapid Launch: Incorrect Encoding of JavaScript Files

I am brand new to learning angular 2, so I am currently attempting to get things up and running following this guide: https://angular.io/guide/quickstart The issue I am facing has left me quite puzzled. Whenever I receive any JS files as a response, they ...

How to incorporate visionmedia debug into an Angular 2 application using System.js, and effective ways to record messages?

Currently I am working on a MEAN stack application with Angular 2 as the frontend. The express backend has successfully utilized debug. However, I am facing issues while trying to import debug cleanly into either app.components.ts or main.module.ts. Any su ...

Setting up the primary and thumbnail Swiper in Angular can be a bit tricky, especially when the initialization is set to false. This tutorial focuses on initializing Swiper 11.0

I have incorporated Swiper into several of my components, and I am facing an issue when Angular routing changes, especially with routeParams like /route/:id – it doesn't work correctly. To tackle this problem, I decided to implement ngZone. Although ...

Error message in Typescript: The argument type '() => () => Socket<DefaultEventsMap, DefaultEventsMap>' cannot be assigned to a parameter of type 'EffectCallback'

I am struggling to comprehend how I should specifically type constrain in order to prevent the error within my useEffect. One approach is to either cast my newSocket or specify the return value of my useEffect as any, but I am hesitant about that solution. ...

Having trouble getting the Next.js Custom Server to function properly with Firebase

I have deployed my Next.js App on Firebase and I am using a custom server (server.ts) to launch the app (node src/server.ts). The code for the server.ts file along with firebaseFunctions.js is provided below. The server.ts file works fine locally, which ...

Discover more efficient methods for utilizing generics in hierarchical objects within typescript

How can I optimize the structure of an object that contains nested objects in Typescript to minimize type repetitions? type itemType = { [key: string]: { [key: string]: { [key: string]: { [key: string]: string } }; }; }; ...

My Nextjs project is encountering deployment issues with both Netlify and Heroku

Whenever I attempt to deploy my application on Heroku or Netlify, I encounter an ERROR related to an incorrect import path. It's perplexing because the import is accurate and functions properly locally. Log ./pages/_app.tsx:7:27 6:31:19 PM: Type err ...

Avoiding the occurrence of routing errors when an error arises in Angular 2

I've observed that whenever an error occurs in my Angular 2 application, it also disrupts the routing. Is there a method to address this and avoid the issue of breaking routing? ...

What is the best way to ensure an observable has been updated before proceeding with additional code execution?

Is an observable the best choice for providing live updates of a variable's value to another class? I have a loop in my service class that looks like this: elements.forEach(element => { doStuff(); this.numberSubject.next(valueFromDoStuff); }) ...