What could be causing a Typescript-defined class property to unexpectedly appear as undefined?

My component has a property called options, which I have defined in the class. However, when I run the code in the browser, it's showing up as undefined. Despite thoroughly checking the code logic, I can't seem to pinpoint any issues. This could be due to a bug or versioning problem.

Below is the component class:

import { Component, OnInit, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-selector',
  templateUrl: './selector.component.html',
  styleUrls: ['./selector.component.css']
})
export class SelectorComponent implements OnInit {

  myControl = new FormControl();
  selectedOption: any;
  filteredOptions: Observable<any[]>;

  @Input() optionTitle: string;
  options: [
    {
      name: 'something'
    },
    {
      name: 'something else'
    }
  ];;

  constructor() {
  }

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
        .startWith(null)
        .map(item => item && typeof item === 'object' ? item.name : item)
        // At this point, the code says that this.options is undefined.
        // (However, console.log(this.optionTitle) works perfectly fine)
        .map(name => name ? this.filter(name) : this.options.slice());
  }

  filter(input: string): any[] {
    return this.options.filter(option =>
      option.name.toLowerCase().indexOf(input.toLowerCase()) === 0);
  }

  displayFn(option: any): string | any {
    return option ? option.name : option;
  }

  select($event): void {
    this.selectedOption = $event.option.value;
  }
}

Here is the error message displayed in the browser:

SelectorComponent.html:3 ERROR TypeError: Cannot read property 'slice' of undefined
    at MapSubscriber.project (selector.component.ts:35)
    at MapSubscriber.webpackJsonp.../../../../rxjs/operator/map.js.MapSubscriber._next (map.js:77)
    at MapSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:89)
    at MapSubscriber.webpackJsonp.../../../../rxjs/operator/map.js.MapSubscriber._next (map.js:83)
    at MapSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:89)
    at MergeAllSubscriber.webpackJsonp.../../../../rxjs/OuterSubscriber.js.OuterSubscriber.notifyNext (OuterSubscriber.js:19)
    at InnerSubscriber.webpackJsonp.../../../../rxjs/InnerSubscriber.js.InnerSubscriber._next (InnerSubscriber.js:23)
    at InnerSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:89)
    at Object.subscribeToResult (subscribeToResult.js:17)
    at MergeAllSubscriber.webpackJsonp.../../../../rxjs/operator/mergeAll.js.MergeAllSubscriber._next (mergeAll.js:85)

What do you think could be causing this issue?

Answer №1

Make sure to initialize the option variable properly. Currently, it looks like this:

options: [
  {
    name: 'something'
  },
  {
    name: 'something else'
  }
];

What you should do instead is:

options = [
  {
    name: 'something'
  },
  {
    name: 'something else'
  }
];

The second code snippet actually initializes the field, whereas the first one is more of a type definition. It's similar to

options: Array<{name: 'something' | 'something else'}>
.

Answer №2

After reviewing your code, it seems like a suitable solution would be to swap out

options:

for

options =

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

Execute AJAX requests at specified intervals with varying data on each run

Every 5 seconds, the code below is executed to retrieve different data each time: For instance: First interval = top level data (level.php) Second interval = top skill data (skill.php) Third interval = top magic data (magic.php) After completing the thir ...

Accessing the Vuex store from external JavaScript files is not allowed

The structure of my application can be found in the following link Architecture of my app For my specific use case, I am looking to utilize getters in the Axios interceptor (/../src/app/shared/services/http-client/http-client.js) to include the authoriza ...

Utilizing Interface Merging: Determining the Appropriate Instance Type for Field Types

I am in need of writing a definition file for an external library. I have augmented a class using interface merging and there are situations where a field of the library class is of the same type as the instance itself. Here is a snippet of demo code: // ...

Issue with CSS not appearing in Google Chrome's coverage tab

As I delve into analyzing the extent of unused CSS on my webpage, I encounter a challenge. The webpage is crafted in Angular 7, with CSS incorporated through the angular.json build configuration. The css appears to be added to the head of the html file, e ...

Upon pressing the browser's back button, the page fails to automatically load with the updated URL

Providing a little context: Let's say I initially access the page using URL1. After that, I use window.history.pushState() to change the URL to URL2. Now, when I click the "back" button, I observe that the address bar displays URL1 again, but the pa ...

Acquire information from the user interface and display it in a highcharts chart using Angular 5

Currently, I am utilizing an npm package for chart creation, which can be found at the following link: https://www.npmjs.com/package/angular-highcharts I have a specific interface set up and I aim to extract values from this interface to populate a line g ...

What's the best approach to ensure Angular 2 routing functions smoothly with App Engine when the page is refreshed?

I'm currently working on an Angular 2 application running in the App Engine Standard Environment. I've managed to get it working smoothly by configuring the app.yaml like this for navigating within the app: handlers: - url: /api/.* script: _go ...

Numerous Cycles Stemming from a Single Answer

My goal is to display a list of products with their details, including a sublist of product models that are checked in the detailed list. The challenge is to achieve this using only one GET request. This means retrieving the JSON data of products once and ...

What is the reason for needing to refresh when submitting form data in a Node application with an HTTP POST

Code Snippet - Angular .state('studentInfo.newStudent', { url : '/new/student', templateUrl: 'students/new-student.html', controller : function($state, $http){ this.saveStudent = func ...

Executing a JavaScript function

I am currently working on an ASP webpage and I am facing an issue with writing JavaScript within it. My goal is to assign a variable to the response of a function that is stored in the code behind (page.aspx.vb). Here is an example of what I am attemptin ...

Is there a way to send a promise resolve or reject from a function code within router.post() in Express?

Below is my code in express (node.js) router.post('/example.json', function (req, res) { // getFileInfo is a function to return an array return getFileInfo(req.body.fileList).then((array) => { axios({ method: 'post', ...

Is there a way to lead to a password-protected page without making it accessible through the URL?

I'm currently honing my skills in web development and embarking on a project to create an interactive puzzle website. The premise is simple - the homepage will feature just an answer input field where users can enter the correct solution to progress t ...

Checking for correct format of date in DD/MM/YYYY using javascript

My JavaScript code is not validating the date properly in my XHTML form. It keeps flagging every date as invalid. Can someone help me figure out what I'm missing? Any assistance would be greatly appreciated. Thank you! function validateForm(form) { ...

Obtaining a response in string format using the $.ajax function

var module = (function(){ return{ loadData: function(url, success, error){ $.when($.ajax({ type: 'GET', cache: false, url: url, contentType: 'application ...

Steps for developing your own node package manager

Looking to create a CLI package manager application called mypkgname for your Github repository? You can easily install this package globally by registering it on npm: npm install -g mypkgname-cli mypkgname init myApp cd myApp npm install npm start Here ...

Refresh jQuery DataTable with updated search results

I have a function that loads the DataTable once the document is loaded. $(document).ready(function() { var $dataTable = $('#example1').DataTable({ "ajax": 'api/qnams_all.php', "dataType": "json", "bDestroy": true, "s ...

Update the Vue method

Is there a way to optimize the following method or provide any suggestions on what can be improved? I am trying to create a function that converts author names from uppercase to only the first letter capitalized, while excluding certain words ('de&apo ...

Three.js Ellipse Curve Rotation

Purpose My goal is to create an EllipseCurve () where a camera will move. The Approach I Took to Achieve the Goal Below is the code snippet for creating the ellipse: var curve = new THREE.EllipseCurve( 0, 0, 1, 1, 0, 2 * Math.PI, false, ...

What is the best way to identify when a disabled button is clicked on in JQM?

I am struggling to grasp how JQM interacts with radio buttons. My code looks like this: <fieldset data-type="horizontal" data-role="controlgroup"> <label for="radio-choice-h-2a"> Brands </label> <input name="radio-choice-h-2" ...

Manipulate CSS Properties with Javascript Based on Dropdown Selection

I am currently working on implementing a feature that involves changing the CSS property visibility: of an <input> element using a JavaScript function triggered by user selection in a <select> dropdown. Here's what I have so far in my cod ...