Error: In Angular 5, the function .next() is not recognized as a valid method for Subjects

I'm attempting to update a Subject named period by calling .next() with a new string, but the console is showing an error saying this.period.next is not a function.

option.component.ts

import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs';

@Component({
    selector: 'app-option',
    templateUrl: './option.component.html'
})
export class OptionComponent implements OnInit {
    public period: Subject<string> = new Subject<string>();

    constructor() {}

    ngOnInit() {}

    setPeriod(period: string) {
        this.period.next(period);
    }
}

option.component.html

<mat-radio-group [(ngModel)]="period" (ngModelChange)="setPeriod($event)">
    <span *ngFor="let option of httpHeader.option"><mat-radio-button [checked]="option.default" [value]="option.param" >{{ option.desc }}</mat-radio-button><br /></span>
</mat-radio-group>

I am using rxjs 5.5.2. The setPeriod function is called upon selecting a radio button.

What could be causing this issue? Using the same method in an HTTP service works fine, but it's not working within this component.

Answer №1

[(ngModel)]="period" facilitates a two-way binding for the period property in your component. It appears to update the period property with the value of the radio group, potentially overriding the Subject instance set during component creation. This could be the reason why the property no longer has the .next method available when calling setPeriod.

A basic usage scenario of mat-radio-group in a template-driven form looks like this:

<mat-radio-group class="example-radio-group"
                 [(ngModel)]="favoriteSeason">
    <mat-radio-button class="example-radio-button" 
                      *ngFor="let season of seasons" [value]="season">
        {{season}}
    </mat-radio-button>
</mat-radio-group>
<div class="example-selected-value">
    Your favorite season is: {{favoriteSeason}}
</div>

...
export class RadioNgModelExample {
    favoriteSeason: string;

    seasons = [
        'Winter',
        'Spring',
        'Summer',
        'Autumn',
    ];
}

Reference: https://material.angular.io/components/radio/examples

If you need to trigger an event on a subject every time there is a change in the radio group selection, it's recommended to use reactive forms instead:

export class Example {
    radio: FormControl = new FormControl();
    period: Subject<string> = new Subject<string>();

    ...

    ngOnInit() {
        this.radio.valueChanges.subscribe(value => {
            this.period.next(value);
        });
    }
}

<mat-radio-group [formControl]="radio">
    <span *ngFor="let option of httpHeader.option">
        <mat-radio-button [checked]="option.default" 
                          [value]="option.param" >
            {{ option.desc }}
        </mat-radio-button>
        <br />
   </span>
</mat-radio-group>

Answer №2

When working with Angular 2/4, the typical way to import is:

import { Subject } from 'rxjs/Subject';

From what I understand, this import method remains the same in Angular 5 as well.

Another thing to note is that you are passing an event as input parameter when calling the function "setPeriod($event)", but the function's definition in the code specifies it should receive a string instead: setPeriod(period: string)

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

Guide to creating a SVG component using typescript in a React application

I have a component where I am passing SVG icons props as an array containing my SVG component data. However, TypeScript is showing me an error while working with Material UI. Type '{ key: number; data: { id: number; icon: ReactNode; }; }' is not ...

Display your StencilJs component in a separate browser window

Looking for a solution to render a chat widget created with stenciljs in a new window using window.open. When the widget icon is clicked, a new window should open displaying the current state while navigating on the website, retaining the styles and functi ...

What is the process for defining an object with a React component as one property and its corresponding props as another property?

Imagine I have an object structured like this: { Component, //<--- the component props, //<--- the props of the component } I want to create a type for this object that can accept a component and automatically infer the type of its props as the ...

Blurry text issue observed on certain mobile devices with Next.js components

There continues to be an issue on my NextJS page where some text appears blurry on certain mobile devices, particularly iPhones. This problem is only present on two specific components - both of which are interactive cards that can be flipped to reveal the ...

How can the dependencies object be extracted from the package.json file in an Angular project?

Scenario: I am managing multiple Angular applications within the same project. Whenever I need to upgrade an npm package, I find myself having to manually update the package.json files in each application. While I attempted a mono repo approach, it did not ...

Encountering a 'scheduler flush execution error' and an Uncaught TypeError due to VueJS and Axios integration

After carefully examining my code, I have pinpointed the cause of this error to the following line: treeNodes.value = documentStore.convertToTree((await axios.get('/File')).data); Initially, I receive a warning: Vue warn]: Unhandled error during ...

Is it possible to utilize Angular translate to support multiple languages for individual components or modules?

Utilizing ngx-translate to switch the language of my application has proven to be quite challenging. My application consists of different languages specifically for testing purposes and is divided into separate modules with lazy loading functionality. As ...

Assign a predetermined value to a dropdown list within a FormGroup

I have received 2 sets of data from my API: { "content": [{ "id": 1, "roleName": "admin", }, { "id": 2, "roleName": "user", }, { "id": 3, "roleName": "other", } ], "last": true, "totalEleme ...

What are some disadvantages associated with using namespaces in Typescript/JavaScript?

After reading various articles on the internet and hearing arguments against namespaces, I am still unsure about the benefits of using modules with a module loader instead. Some claim that namespaces are outdated and problematic, but I'm not convinced ...

Filtering an array using criteria: A step-by-step guide

Currently, I am developing a system for Role Based permissions that involves working with arrays. Here is an example of the array structure I have: let Roles = { [ { model: 'user', property: 'find', permission: 'allow' ...

Awaitable HttpResponseError

My challenge is that I'm attempting to handle a HttpError or HttpErrorResponse using an observable. However, the only option I have is to handle the HttpResponse, which is necessary but not sufficient. I also need to find a way to avoid this limitatio ...

Enhance the step implementation in Cucumber-js

Background In my TypeScript project, I am utilizing https://github.com/cucumber/cucumber-js. The code snippet below showcases a typical cucumber implementation: import { Given, Then, When } from 'cucumber' Given(`Page is up and run ...

Trigger Screen Reader to Announce When a Component Is Deleted

When the last filter item is removed, I want the screen reader to announce "All Filters Are Removed." However, if the active filter component is removed without any other element to assign an aria-label attribute, I'm not sure how to handle this situa ...

The type '{}' is lacking the specified attributes from type 'RouteComponentProps<{},,>'

As a newcomer to React and Typescript, I'm in the process of familiarizing myself with both. Please bear with me as I navigate through this learning curve! index.tsx Router.tsx (containing all route definitions) LandingFrame.tsx (defining the page la ...

Position the div beneath another div using the display:grid property

I can't seem to figure out how to position a div below another div using display:grid. The div is appearing on top instead of below. The "app-bm-payment-card-item" is actually a custom Angular component. Here's the HTML file: //div wrapper < ...

Is there a way to obtain an array after subscribing to an RxJS method?

I am struggling with the following code snippet: Rx.Observable.from([1,2,3,4,5,6]) .subscribe(x=>console.log(x)); Is there a way to modify this code so that instead of iterating through the array elements from the .from() method, I can return the enti ...

The absence of the import no longer causes the build to fail

Recently, after an update to the yup dependency in my create react-app project, I noticed that it stopped launching errors for invalid imports. Previously, I would receive the error "module filename has no exported member X" when running react-scripts buil ...

Is Typescript generating error TS2411 within its own Typescript module?

After transitioning to using @types in Typescript 2.0, I executed npm i -S typescript @types/typescript to ensure everything was set up correctly with typescript. However, whenever I run tsc on my project and exclude "node_modules", I encounter the same e ...

Utilize *ngFor in Angular to showcase values from a nested map

In my Angular component, I have an array structured as follows: map: Map<string, Map<string, string>>; The specific value I want to display in the user interface is located within the second map. My approach involves iterating over the map a ...

Utilizing declaration files in a TypeScript application to provide global exposure of types

Recently, I've delved into the world of typescript and set up a project with numerous React components written in typescript. To streamline development, we decided to extract all necessary types for these components into a separate file named types.d. ...