Error: Attempting to access the 'subscribe' property of an undefined value (Observable)

In my TypeScript/Angular2/SPFx project, I have the following code snippet:

// Populate the regulatory documents dropdown
this.regulatoryDocumentsService.fetchRegulatoryDocumentsData().subscribe(
    data => { this.regulatoryDocumentsData = data },
    err => { window.console && console.log(err) }
);

Explaining further:

public fetchRegulatoryDocumentsData(): Observable<RegulatoryDocument[]> {
    var choicesArray: Array<RegulatoryDocument> = new Array<RegulatoryDocument>();

    // Handling local environment
    if (Environment.type === EnvironmentType.Local)
    {
        // Providing dummy data for the form - it works
        window.console && console.log("fetchRegulatoryDocumentsData(): Local workbench in use");
        choicesArray.push(new RegulatoryDocument(1,"Document 1"));
        choicesArray.push(new RegulatoryDocument(2, "Document 2"));
        choicesArray.push(new RegulatoryDocument(3, "Document 3"));
        return Observable.of<RegulatoryDocument[]>(choicesArray);
    }
    else if (Environment.type == EnvironmentType.SharePoint || 
          Environment.type == EnvironmentType.ClassicSharePoint)
    {
        // Issue arises here when subscribing to fetchRegulatoryDoocumentsData() due to undefined
        pnp.sp.web.lists.getByTitle('Regulatory Documents').items.get().then((choices: any[]) => {
            window.console && console.log("choices ...");
            window.console && console.log(choices);

            if (choices) {
                [].slice.call(choices).forEach(choice => {
                   choicesArray.push(new RegulatoryDocument(choice.ID, choice.Title));
                });
            }
            return Observable.of<RegulatoryDocument[]>(choicesArray);
        });
    }
}

However, encountering an issue when

Environment.type != EnvironmentType.Local
, as a subscription error occurs mentioning inability to subscribe to undefined. The suspicion falls on the nested PNP promise structure. Any suggestions or insights would be highly appreciated.

Answer №1

When you use lists.getByTitle('Regulatory Documents').items.get().then(...);
in your code, it will give you a promise containing an observable.

However, if (Environment.type == EnvironmentType.SharePoint || 
          Environment.type == EnvironmentType.ClassicSharePoint)
    {
        // The function fetchRegulatoryDoocumentsData() is undefined when I attempt to subscribe to it.
    return Observable.create( (observer: any) => {
        pnp.sp.web.lists.getByTitle('Regulatory Documents').items.get().then((choices: any[]) => {



            window.console && console.log("choices ...");
            window.console && console.log(choices);

            if (choices) {
                //choices.forEach((choice) => {
                //    choices.push(new Rating(choice));
                //});
                //Array.from(choices).forEach(function (child) {
                //    window.console && console.log(child)
                //});

                [].slice.call(choices).forEach(choice => {
                   choicesArray.push(new RegulatoryDocument(choice.ID, choice.Title));
                });
            }
            observer.next(choicesArray);
        });
    });
  }
}

You can also choose to utilize promises throughout your code:

this.regulatoryDocumentsService.fetchRegulatoryDocumentsData().then(
    data => { this.regulatoryDocumentsData = data },
    err => { window.console && console.log(err) }
);

service

public fetchRegulatoryDocumentsData(): Observable<RegulatoryDocument[]> {
    var choicesArray: Array<RegulatoryDocument> = new Array<RegulatoryDocument>();

    // Local environment
    if (Environment.type === EnvironmentType.Local)
    {
        // Send dummy data to the form - this works
        window.console && console.log("fetchRegulatoryDocumentsData(): Local workbench in use");
        choicesArray.push(new RegulatoryDocument(1,"Document 1"));
        choicesArray.push(new RegulatoryDocument(2, "Document 2"));
        choicesArray.push(new RegulatoryDocument(3, "Document 3"));
        return Promise<RegulatoryDocument[]>.resolve(choicesArray);
    }
    else if (Environment.type == EnvironmentType.SharePoint || 
          Environment.type == EnvironmentType.ClassicSharePoint)
    {
        // The function fetchRegulatoryDoocumentsData() is undefined when I try to subscribe to it.
        pnp.sp.web.lists.getByTitle('Regulatory Documents').items.get().then((choices: any[]) => {
            window.console && console.log("choices ...");
            window.console && console.log(choices);

            if (choices) {
                //choices.forEach((choice) => {
                //    choices.push(new Rating(choice));
                //});
                //Array.from(choices).forEach(function (child) {
                //    window.console && console.log(child)
                //});

                [].slice.call(choices).forEach(choice => {
                   choicesArray.push(new RegulatoryDocument(choice.ID, choice.Title));
                });
            }
            return choicesArray;
        });
    }
}

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

How to create an array of objects in Angular 2

Can someone please help me understand how to set up an array of objects so that I can add items to it later on? Here's what I currently have: tab: [{tel:number, name:String}]; ...

Using TypeScript for Immutable.js Record.set Type Validation

Currently, I'm utilizing Immutable.js alongside TypeScript for the development of a Redux application. In essence, the structure of my State object is as follows: const defaultState = { booleanValue: true, numberValue: 0, } const StateRecord = ...

Utilize FastClick for improved speed and response on

I have been trying to use FastClick in my TypeScript project with FastClick.d.ts. My TSC configuration uses "module: commonjs" and I am bundling everything with Webpack. However, I am having trouble referencing FastClick properly. When I try to import Fas ...

Tips for customizing Material UI's styled() SVG icon to accept SVG icon as a react component:

Currently, I have functioning code that uses the "any" type for props. When transitioning to MUI v5 and using the mui v4 makeStyles, this approach raises compatibility issues that were not present before. // Import SVG Icons components import { ReactCo ...

Save this code snippet to your clipboard using vanilla JavaScript (no jQuery needed)

I am working on an Angular 9 application where I want to implement the functionality of copying the URL to clipboard when clicked. Currently, I have the following code: The issue I am facing is that it only copies the URL on the second attempt and then st ...

Ways to verify the existence and non-empty status of a directory?

zip.loadAsync(files).then(function(directory:any){ if (directory.folder("Mary")){ console.log("fail"); } else{ directory.folder("Mary").forEach(function (filename: any) {Console.log(filename);}); }; } I am attem ...

Limit the implementation of Angular Material's MomentDateAdapter to strictly within the confines of individual

Within my app, I have several components that utilize the mat-datepicker. However, there is one component where I specifically want to use the MomentDateAdapter. The issue arises when I provide it in this one component as it ends up affecting all the other ...

Encountering a 404 error when trying to load a script from a local folder into a component

I've been attempting to load a JavaScript file into a component. When the file is placed outside the 'src' folder, everything works perfectly. However, when it's inside the 'src' folder, I keep getting a 404 error. I've t ...

Saving information obtained through Angular subscribe into a variable

One of the services I have is called getWeather, which contains a method that communicates with an API using longitude and latitude parameters and then returns the response: import { Injectable } from '@angular/core'; import { HttpClient } from ...

Using `publishReplay()` and `refCount()` in Angular does not behave as anticipated when dealing with subscriptions across multiple components

I am currently investigating the functionality of publishReplay in rxjs. I have encountered an example where it behaves as expected: const source = new Subject() const sourceWrapper = source.pipe( publishReplay(1), refCount() ) const subscribeTest1 = ...

The error message "Ionic 3 encountering issues with accessing property 'valid' from undefined or null reference"

As I was setting up a form on a CRUD using Firebase, initially just storing name and number as string types, I decided to add more parameters of the same type. However, I encountered an issue with the error message "Unable to get property 'valid' ...

Which specific files do I have to edit in order for Laravel to acknowledge a new data type?

Currently, I am honing my skills in Laravel by working on a Laravel Breeze application. One task that I have set for myself is to incorporate a postal code field into the existing User model, including the registration form. To tackle this challenge, I dec ...

The Angular/Express application is in search of outdated JavaScript files within the Chrome browser

When updating and deploying my Angular web app on Google App Engine with an Express server, I encounter a peculiar issue. Upon refreshing the browser, I sometimes face a blank page accompanied by the following error: main.f2b54282bab6f51a.js:1 Failed to lo ...

Creating an object key using a passed literal argument in TypeScript

Can the following scenario be achieved? Given an argument, how can we identify the object key and access it? Any potential solutions? async function checkKey(arg:'key1'|'key2'){ // fetchResult returns an object with either {key1:&apo ...

Creating and updating a TypeScript definition file for my React component library built with TypeScript

As I work on developing a React library using TypeScript, it is important to me that consumers of the library have access to a TypeScript definition file. How can I ensure that the TypeScript definition file always accurately reflects and matches the Java ...

Angular 2 forms are displaying ngvalid when input fields are marked as nginvalid

The form displays ngvalid because I have included the code like this: <form novalidate class="pop-form" (submit)="signUp()" #regForm="ngForm"> <div class="group"> <input type="text" [(ngModel)]="signUpData.name" [ngMode ...

Uncertainty surrounding dynamic bootstrapping in @NgModules

After successfully installing rc7, my module and component are functioning as expected. Now, I am looking to utilize it on a webpage by only bootstrapping modules and components if the current page contains the necessary selector. Although I have declare ...

Utilize the imported function from <Script> within NextJS

When working with vanilla JS, I am able to include a script like this: <head> <script src="https://api.site.com/js/v1/script.js"></script> </head> and then create an instance of it using: const fn = ScriptJS(); I can t ...

The BehaviorSubject will consistently emit identical values to each subscription

I am currently facing an issue with the BehaviorSubject where it emits a value for every subscription. This means that if I have, for example, 2 subscriptions to this.projectService.projectState$ streams using methods like async or tap, the projectState$ e ...

Navigate to the logout page upon encountering an error during the request

I recently upgraded our application from angular 2 to angular 5 and also made the switch from the deprecated Http module to the new HttpClient. In the previous version of the application, I used the Http-Client to redirect to a specific page in case of er ...