Error: Unable to access the 'next' property of null within an Angular 2 Observable

Issue Found

An error of type TypeError has occurred: Cannot read property 'next' of null

Problematic Template Utilizing Observer.next

import { NavService } from '../../providers/services/nav-service/nav-service';

@Component({
  selector: 'ion-header',
  providers: [NavService],
  template: `
    <ion-navbar>
        <ion-title>{{navService.getCurrentName()}}</ion-title>
        <ion-buttons start>
            <button (click)="navService.goHome()">
                <span primary showWhen="ios">Cancel</span>
                <ion-icon name="md-close" showWhen="android,windows"></ion-icon>
            </button>
        </ion-buttons>
    </ion-navbar>
  `
})

Service implementing Observable Functionality

import { Platform } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { Injectable, ViewChild } from '@angular/core'

@Injectable()

export class NavService {
private dismissObserver: any
public  dismiss: any

constructor (
    private authService:    AuthService,
    private platform:       Platform
) {
    this.dismissObserver = null;
    this.dismiss = Observable.create(observer => {
        this.dismissObserver = observer;
    });
}

public goHome():void {
    this.dismissObserver.next(true);
}

Code Snippet for app.ts with Subscription

@Component({
    providers: [NavService]
})

export class MyApp {

  @ViewChild(Nav) navController: Nav
  constructor(
    public navService: NavService

) {
    this.initializeApp()
  }

 initializeApp() {

    this.platform.ready().then(() => {

        StatusBar.styleDefault()
        this.setRoot()
        this.navController.setRoot(HomePage);

        this.navService.dismiss.subscribe((event) => {
            console.log ("event", event);
            this.navController.setRoot(HomePage)
        })
    })
}

ionicBootstrap(MyApp, [])

By the way, I am following this helpful "tutorial":

Ionic2, inject NavController to Injectable Service

Answer №1

When you use Observable.create to assign dismissObserver, it only happens when dismiss is subscribed to. If you call goHome before that subscription occurs, then dismissObserver will be null and an error will occur.

Alternatively, what you're essentially creating with dismiss and dismissObserver is a Subject. To implement this, replace your NavService constructor and goHome method with the following code:

constructor (
  private authService:    AuthService,
  private platform:       Platform
) {
  this.dismiss = new Subject();
}

public goHome():void {
  this.dismiss.next(true);
}

By making this change, you can avoid getting errors even if a subscription comes after the emission of values. Consider using BehaviorSubject instead of Subject if you want to cache a single value for subsequent subscriptions.

EDIT: Don't forget to import the Subject module by adding

import { Subject } from 'rxjs/Subject';

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 is the method for making an interface extension from a type as optional?

Can you help me create an interface that includes all students and part of a school, ensuring that gender is required for Peter and optional for other students? export type School = { address: string; state: string; }; export type Gender = { gender: ...

Is it possible to integrate a collection of libraries along with external dependencies into Vite?

Currently, I am in the process of packaging a library for npm that uses type: "module". To accomplish this, I have configured vite's library mode with the following settings: export default defineConfig({ css: { postcss: { plugin ...

Printing values of an object in an Angular/HTML script is proving to be quite challenging for me

In my Angular project, I have created a service and component for listing objects. The list is functioning correctly as I have tested it with 'console.log()'. However, when I try to display the list on localhost:4200, nothing appears. <table&g ...

How should I set up my TestBed configuration in Jasmine test scenarios within an Angular environment?

As I begin writing test cases for Angular, I've come across various ways to configure my TestBed by reading articles online. Here are a few examples: Example 1: beforeEach(async(() => { TestBed.configureTestingModule({ ... }).compileCompone ...

React: Issue accessing URL parameters using useParams() within a nested component

In my demo application, there are two components - QuoteDetail and Comments. Both require URL parameters, but I am only able to access them in the parent component. App.tsx: <Switch> // ... <Route path="/quotes" exact> <Al ...

The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows: export class Workout { id: string; name: string; exercises: Exercise[]; routine: Ro ...

The function for utilizing useState with a callback is throwing an error stating "Type does not have

Currently, I am implementing the use of useState with a callback function: interface Props { label: string; key: string; } const [state, setState] = useState<Props[]>([]); setState((prev: Props[]) => [...pr ...

Encountered an issue with the core-js postinstall script, causing a failure

I encountered the following errors while attempting to install node modules in an existing Angular project. The installation is being carried out on a Windows machine (Win32 X64). > [email protected] postinstall node_modules\babel-runti ...

Utilizing Loops to Generate Unique CSS Designs on an HTML Page

View reference image ->Take a look at the reference image provided. ->In the image, a for loop is used to create box designs and displayed above. ->The goal is to change the background color and border color of all boxes using a single HTML cla ...

Exploring the distinctions between types and classes through type hinting

It seems that I am facing some challenges with this task and the reason is unclear to me switch (typeof request) { case 'EnrollmentRequest': The type '"EnrollmentRequest"' cannot be compared to the type '"string" | "number" | ...

Unable to create an Ionic module with routing using Angular

Having trouble generating modules with routing in my Ionic project. After creating a new Ionic project using ionic start routing blank, I attempted to generate a module with routing by entering the following commands: ionic g m heroes --route heroes --mo ...

Disable multiple buttons at once by clicking on them

What is the best way to disable all buttons in a menu when one of them is clicked? Here is my code: <div class="header-menu"> <button type="button"> <i class="fa fa-search" matTooltip="Filter"& ...

What is the best way to incorporate additional data into a TypeScript object that is structured as JSON?

I'm exploring ways to add more elements to an object, but I'm uncertain about the process. My attempts to push data into the object have been unsuccessful. people = [{ name: 'robert', year: 1993 }]; //I aim to achieve this peopl ...

How to simulate loadStripe behavior with Cypress stub?

I am struggling to correctly stub out Stripe from my tests CartCheckoutButton.ts import React from 'react' import { loadStripe } from '@stripe/stripe-js' import useCart from '~/state/CartContext' import styles from '. ...

Error message: Cypress Vue component test fails due to the inability to import the Ref type (export named 'Ref' is missing)

Recently, I created a Cypress component test for my Vue component by mounting it and verifying its existence. The component utilizes Vue's Ref type and is structured as a TypeScript component. However, during the test execution, Cypress encountered a ...

Accessing the 'comment' property within the .then() function is not possible if it is undefined

Why does obj[i] become undefined inside the .then() function? obj = [{'id': 1, 'name': 'john', 'age': '22', 'group': 'grA'}, {'id': 2, 'name': 'mike', &apo ...

The search functionality in the unit test could not be executed as it is

Encountering an error this.sourceAccounts.find is not a function while running unit test on an array. component.ts: sourceAccounts: Array<IObject>; nameChangedSubscription: Subscription; constructor(private accountService: AccountService) { } ngOn ...

The RC-dock library's 'DockLayout' is not compatible with JSX components. The instance type 'DockLayout' is not a valid JSX element and cannot be used as such

Despite encountering similar questions, none of the provided answers seem to address the issue within my codebase. My project utilizes React 17, Mui v5, and TS v4. I attempted to integrate a basic component from an external package called rc-dock. I simply ...

Sending data to a parent component from a popup window in Angular Material using a button click while the window is still open

How can I retrieve data from an Angular Material Dialog Box and send it to the Parent component? I am able to access data after the dialog box is closed. However, I am wondering if there is a way to retrieve data while the dialog box is still open, especi ...

I encountered a warning while using the useViewportScroll in NextJs with Framer Motion: "Caution: The useLayoutEffect function does not have any effect on the server

Successfully implementing NextJs with Framer Motion, yet encountered a warning: Warning: useLayoutEffect does not function on the server due to its effect not being able to be encoded in the server renderer's output format. This may cause a differenc ...