Promise rejection error: Unable to create Rx_1.Subject as a constructor ; Zone: ; Task: Promise.then ; Error Value: TypeError: Rx_1.Subject is not a constructor

My Angular 2 app uses systemjs for mapping/loading.

While importing rxjs in the project and referencing it works fine, deploying the code results in a failure to construct a Subject variable with the error message:

"Unhandled Promise rejection: Rx_1.Subject is not a constructor ; Zone: ; Task: Promise.then ; Value: TypeError: Rx_1.Subject is not a constructor".

Rx on systemjs:

(function (global) {
var map = {
    'app': 'app',  
    '@angular': 'js/@angular', 
     // other libraries...
    'rxjs': 'js/rxjs', 
};

// packages tells the System loader which filename and/or extensions to look for by default

var packages = {
    'app': { main: 'main.js', defaultExtension: 'js' },
    'rxjs': { defaultExtension: 'js' }
};

The way I am instantiating the subject:

import { Injectable } from '@angular/core';
import { Subject } from "rxjs/Rx";

@Injectable()
export class MyService {

constructor(private http: Http) {
    let b = new Subject<string>(); // exception HERE
    let m = b.asObservable(); 
    b.next("k");

All of rxjs is loaded fine in the browser.


UPDATE: Upon further investigation, if I import Rx in my Angular service as:

import * as Rx from 'rxjs/Rx';

and then inspect the Rx object in the console, it only has a default, and __useDefault property getter. However, all other features like Observable and Subject are accessible through them.

For example:

var observable = Rx.Observable.create(function (observer) {
        observer.next(1);
    });

results in:

VM1083:1 Uncaught TypeError: Cannot read property 'create' of undefined

whereas, using:

var observable = Rx.default.Observable.create(function (observer) {
        observer.next(1);
    });

everything works correctly.

My project is in TypeScript, and I have tried compiling targeting ES5 and ES6.

Answer №1

Previously, I was using the syntax 'import { Subject } from 'rxjs/Subject''. I now switched to 'import { Subject } from 'rxjs'', which successfully fixed the problem I encountered.

Answer №2

An instance of the Subject is demonstrated in this scenario

@Injectable()
export class EventService {

    public eventSubject:Subject<any> = new Subject();

    constructor() {}
}

This online resource provides a comprehensive guide on Utilizing Observables for learning about Observables.

Answer №3

After discovering the solution on How to import `Observable` from `Rx` (not angular), I successfully unblocked my progress.

By updating my tsconfig.json module to "commonjs", the Rx library files are now transpiled smoothly without any issues related to getters.

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

Finding the appropriate method to access a template variable reference in a designated row of an Angular Material table (Angular 7)

Currently, I am working on implementing a more intricate version of a behavior inspired by Angular Material's tutorials. In my simplified example, an Angular Material table is populated with data from a string array. The first column contains input fi ...

Tips for developing projects that are compatible with various versions of Angular, including Angular 2, 4, 5,

I have a Windows 8 system with Angular CLI version 6.1.1 installed. I am trying to create projects for Angular versions 2, 4, 5, and 6. However, when I use the command below to create a new project: ng new demo The package.json file contains the follow ...

Display the label and hide the marker on the map

I have integrated openStreetMap into my Angular 6 application as shown below. Adding a marker to the map works perfectly fine, but displaying a label when the marker is clicked seems to be a challenge for me and I'm unsure why. Additionally, I am puzz ...

A guide on resolving deprecated warnings for typographical errors

Every time I try to npm install I am bombarded with numerous errors. typings WARN deprecated 9/9/2016: "registry:dt/node#6.0.0+20160831021119" is deprecated (updated, replaced or removed) My experiences with typescript have been nothing but a series ...

Adding pixels to the top position with jQuery in Angular 2

I am trying to adjust the position of my markers when the zoom level is at 18 or higher by adding 10px upwards. However, my current approach doesn't seem to be working as expected. Can someone please assist me with this issue? You can view the code sn ...

Issue with saving date values accurately in Nestjs/Prisma

After logging the response body before saving it to the database, I noticed that the shape is correct. Here's what it looks like: //console.log response body CreateOpenHourDto { day: 'WEDNESDAY', startTime: 1663858800000, endTime: 16638786 ...

Steps for producing an interactive Material UI Icon Atom in StoryBook and React TypeScript

I have integrated StoryBook with React, TypeScript, and Material UI. My goal is to create a dynamic Icon Atom component that can render different icons based on the props passed to it. Currently, I am facing issues with my current approach. Specifically: ...

Why is the mat-toolbar and mat-toolbar-row in the footer (shared) component of Angular 6 not showing up correctly, despite no error being reported?

Despite reviewing similar questions, I have not been able to find a solution for my specific issue. I have searched through the following links but failed to find a solution: Angular Material v6 Mat-Footer - "Cannot read property 'template' of ...

I encountered a SyntaxError while parsing JSON due to an absence of a number after a minus sign at position 1

I am trying to use the replicate model visoar/product-photo:edf42659dae0da88a26dba4912e7e4bb6c2fba25b1e1c6a5464cf220e467bce0, but when I provide it with an image and a prompt like on this page.tsx: "use client" import { LandingNavBar } from &apo ...

I want to remove an object from my Django Rest Framework (DRF) database using Angular 13

After receiving the id that needs to be deleted, I noticed that the last line of code in service.ts for the delete method is not being executed. The files and code snippets I utilized are: COMPONENT.HTML <li *ngFor="let source of sources$ | async ...

The error message "DOMTokenList is not an array type" occurred when attempting to use the spread operator on a DOMTokenList

Encountered an issue with the 'DOMTokenList' not being recognized as an array type while trying to convert it using a spread operator. Utilizing Typescript/Playwright for automation purposes, I am attempting to access the classlist of a div eleme ...

MaterialUI Divider is designed to dynamically adjust based on the screen size. It appears horizontally on small screens and vertically on

I am currently using a MaterialUI divider that is set to be vertical on md and large screens. However, I want it to switch to being horizontal on xs and sm screens: <Divider orientation="vertical" variant="middle" flexItem /> I h ...

Enhancing Image Quality with .NET Core 2 and Angular 5 Compression Techniques

I have a question regarding image compression on my website. I currently use g-zip to reduce the size of js/html/css files, but I'm unsure about how to handle image compression. Should images be compressed before being uploaded to the server or is the ...

When executing NextAuth with the given auth options, it raises an error message stating "Incompatibility of types for 'adapter.createUser' between these specific types."

Currently, I am working on a project using Next.js 14 and attempting to configure NextAuth with the app/router. Unfortunately, I have encountered a type error that is proving difficult to resolve. Below is my route.ts file: // ./app/api/[...nextauth]/rout ...

When using Angular msal_angular in conjunction with an ASP.NET Core Web API, an error may occur indicating an invalid token

I developed my Angular application using the guide provided in this example: https://github.com/microsoftgraph/msgraph-training-angularspa Successfully, I managed to log in and authenticate with MS Graph from within the Angular app. However, I am facing ...

What could be the reason for my FormData object being consistently devoid of content?

I am attempting to populate formData with data using the following method: params = {'code': 'h1'} const formData: FormData = new FormData(); formData.append('parameters', JSON.stringify(params)); Once I attempt to access th ...

Guide on displaying the login component as the initial view upon app initialization instead of the app component in Angular 5

Just starting out with Angular 5 and looking to implement a login page as the initial screen of my app. Currently, my appComponent displays a toolbar and side navigation bar. However, I want to first show a login screen upon app load. Once the user succes ...

Unable to display content within the router-outlet

I'm currently attempting to dynamically change the router outlet based on authentication status. My code looks something like this: <div *ngIf="isLoggedIn" class="layout-wrapper layout-2" [ngClass]="{'layout-loading&ap ...

What causes the canLoad function to create an endless loop when rerouting?

Utilizing Angular's canLoad function in my AuthGuard to authenticate a lazy loaded module at the root of my application. If the user is not authenticated, the module will not load and the user will be directed to the login page. This process works sm ...

ag-Grid open-source server-side filtering

Currently, I am utilizing the ag-grid community version for my project. I am inquiring whether it includes support for server side filtering and paging. If not, what alternative methods can be used to implement filtering with the ag-grid community versio ...