There seems to be a problem: "Type Error - undefined is not

I've encountered an error while attempting to subscribe to my observable in a Server Sent Event class that observes other components and sends information to them. Is anyone familiar with how to resolve this issue?

Here is the Server Sent Event class:

@Injectable()
export class ServerSentEvent implements OnInit{
  public observable : Observable<any>;
  ngOnInit(){
    var errorCount = 0;
    this.observable = Observable.create(observer => {
      var eventSource = new EventSource(filterUrl);
      eventSource.onmessage = (event: any)=>{
        console.log("received val: " + JSON.parse(JSON.parse(event.data).payload).value);
        observer.next(JSON.parse(JSON.parse(event.data).payload).value);
      }
      eventSource.onerror=(error: any)=>{
        errorCount++;
        if(error.targer.readyState === 0 && errorCount > 5){
          eventSource.close();
          observer.error();
        }
      }
      return() => {
        eventSource.close();
      };
    });
  }
}

And here is my LightController class:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers:[ServerSentEvent]
})
export class LightControler implements OnInit{
  connected : boolean;
  light : boolean;
  public button = (<HTMLInputElement>document.getElementById("check-toggle"));
  public slider = (<HTMLInputElement>document.getElementById("light-slide"));
  public slid = (<HTMLProgressElement>document.getElementById("light-bar"));

  public constructor(
    private http : HttpClient,
    private serverSentEvent: ServerSentEvent){
    this.serverSentEvent.observable.subscribe(
      {
        next: val =>{
          console.log("light val: "+ val);
          this.slid.value = val;
          if (val >= 1){
            this.light = true;
            this.button.checked = true;
          }
          else{
            this.light = false;
            this.button.checked = false;
          }
        },
        error: error =>{
          setTimeout(()=> serverSentEvent.ngOnInit(), 1000);
        }
      }
    );
  }

The error occurs at this point: this.serverSentEvent.observable.subscribe()

TypeError: undefined is not an object (evaluating 'this.serverSentEvent.observable.subscribe')

It seems that the ngOnInit of the ServerSentEvent isn't initialized when the constructor of the LightControler is executed, causing an attempt to subscribe to a non-existent observable.

To fix this issue, I must call serverSentEvent.ngOnInit() before subscribing to the observable.

Answer №1

Make sure to pass a function instead of an object to the subscribe function. Adjust your code as follows:

this.serverSentEvent.observable.subscribe(
  val => {
      console.log("received value: "+ val);
      this.slid.value = val;
      if (val >= 1){
        this.lightOn = true;
        this.switch.checked = true;
      }
      else{
        this.lightOn = false;
        this.switch.checked = false;
      }
    },
    error => {
      setTimeout(()=> serverSentEvent.ngOnInit(), 1000);
    });

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

Understanding the Purpose of the Pipe Function in Angular 2 and Typescript Observables

Recently, I encountered a situation where I needed to accept an Observer parameter in a function written in Typescript. I struggled to find a solution, reminding me of working with a delegate parameter in C#. The specific scenario involved adding a bookend ...

Using knockout to retrieve the attribute value with an onClick event

Snippet of HTML View with attribute value 'Qref'. This is the sample HTML Code for binding Currently, I have manually inputted the Qref Attribute value <!--ko if:$parent.Type == 2 --> <input type="checkbox" data-bind="attr:{id: $data ...

I am encountering an issue with express-session where it is failing to assign an ID to

Seeking assistance with utilizing express-session to manage user sessions on arcade.ly. I have not specified a value for genid, opting to stick with the default ID generation. However, an ID is not being generated for my session. An example of the issue c ...

Unable to set selected property in React Material-UI menu item

One issue I'm facing is setting the selected prop using react mui menu item. In a multiple select menu list, there's a field called allValues that, when clicked, should toggle the selection of all menu items. The code for this functionality looks ...

Converting dates in Javascript

I have retrieved a date/time value of "20131218" from an API response. My goal is to transform this date into the format "2013-12-18". In PHP, this can be easily achieved with the following code: echo date("Y-m-d", strtotime('20131218')); The ...

Why is the checkmark still displaying red when it should be showing as green?

Are you struggling with password strength on your website? I faced a similar issue where the checkmarks remained red despite my attempts to turn them green. If you want to change the checkmark color, here is some code that may help: document.getElementBy ...

Creating a pure function in JavaScript and React: A step-by-step guide

I am dealing with a dataset structured as follows: const arr_obj = [ { id: '1', children: [], type: 'TYPE1', }, { id: '2', children: [ { id: &apos ...

What are some techniques for improving the performance of this Javascript function?

I implemented a procedure to change the style of my top navigation bar based on the user's scroll position on the page: /* Handling changes in the top nav during page scrolling */ window.onscroll = function () { if ($(window).scrollTop() > 150 ...

Directives for components and the NgModule

My goal is to divide a component into three separate sections. To achieve this, I created a new component along with its template. However, now I am facing the challenge of including these child components into the main component in order to ensure that th ...

Updating a Json array by including a new property using the Gson library

Using Gson, I am serializing a list of objects in the following manner: String responseMessage = new Gson().toJson(pages.get(pagenumber)); Now, I want to include an additional property that can be accessed in JavaScript, which is not related to the list ...

Javascript use of overlaying dynamically generated Canvases

Currently, I am developing a game to enhance my skills in HTML5 and Javascript. In the beginning, I had static canvases in the HTML body but found it difficult to manage passing them around to different objects. It is much easier for me now to allow each ...

Angular 8 seems to be disregarding SetTimeout

When executing the following code snippet: this.logger.warn('start'); setTimeout(() => {},3000); delay(3000); this.logger.warn('start2'); The output displays enter image description here Blockquote: ngx-logger.js:596 2020-11-19T13 ...

Excel add-in in Angular featuring exclusive custom functions

I've recently embarked on the journey of developing Office Add-ins, using public code samples to simplify the process. Currently, I am exclusively testing with the web version of Excel. My goal is to merge the functionality of two sample add-ins: one ...

In need of a method to create PDFs using client-side technology (specifically AngularJS)?

I need a method to create PDFs using AngularJs that includes HTML, CSS, and JavaScript elements. I have tried two options: jsPDF (which does not support CSS) Shrimp (built on Ruby) Neither of these solutions fit my needs. Is there another way to accom ...

Controller experiencing peculiar AJAX response in CodeIgniter

I recently embarked on a Codeigniter project and now I'm faced with the task of making an AJAX call to a specific controller. Here is the scenario: - I have two dropdown menus: one for selecting counties and the other should populate with cities with ...

unable to initiate a new project in angular version 8

Upon attempting to add a new project in Node.js command prompt, I encountered an error message stating: "The system cannot find the path specified." This has left me perplexed about how to proceed with creating a new project. Your environment is configure ...

Searching and Sorting through JSON Data in React Native

I am currently expanding my knowledge in React Native and experimenting with filtering a JSON data set on a screen. My goal is to display only the filtered results on the screen. Would it be advisable for me to create a new component called FilteredTicket? ...

How can the center element be aligned without recursively centering all children?

How can I center all children within a particular element without affecting their children? <Col style={{ textAlign: "center" }}> <Space>...</Space> <div>...</div> </Col> In this scenario, I am utilizing t ...

Creating pages or tabs within a table using HTML5 and Angular is a simple and effective way to organize

I have a REST response that returns around 500 records. These records are being displayed in an Angular table. I would like to add customization options for the user, allowing them to choose to display 10/20/30... records per page. Additionally, I want to ...

Retrieve, establish cookies, and guard against CSRF attacks

Having some difficulty with CSRF in my application while using Isomorphic fetch. The backend sends a CSRF-TOKEN in the set-cookies property: https://i.sstatic.net/duODj.png There is advice against directly accessing these cookies in code, so I attempted ...