angular-cli encounters an issue: attempting to access a property that does not exist on type 'void'

Currently in the process of migrating an Angular 2 project to Angular 4 and also updating the angular-cli to the latest version 1.0. Unfortunately, there is no Ahead-of-Time compilation (AOT) implemented in the application.

An issue has arisen with a component in the app during the build process, although it does not show any errors in the IDE (Visual Studio 2017 Professional).

The specific error messages encountered during the build are as follows:

ERROR in .../src/app/shift-list/shift-list.component.ts (163,88): Property 'userRank' does not exist on type 'void'.

ERROR in .../src/app/shift-list/shift-list.component.ts (176,90): Property 'userPlatoon' does not exist on type 'void'.

Below is a condensed version of the problematic component code:

@Component({
  selector: 'ksm-shift-list',
  templateUrl: './shift-list.component.html',
  styleUrls: ['./shift-list.component.css'],
  providers: [
      DnnService
  ]
})
export class ShiftListComponent implements OnInit {

    ...
    userRank: string;
    userPlatoon: string;
    ...

    constructor(
        private _dnn: DnnService) { }

    // On Init  ********************************************************
    ngOnInit(): void {
        this.getDepartmentAndOptions();
    }

    // #################################################################
    //                        LIST OPTIONS
    // #################################################################

    getDepartmentAndOptions(): void {
        this._dnn.getOptionsAndProfile()
            .subscribe(
            data => {
                this.appOptions = data;

                this.ptnList = this.appOptions.Platoons;
                this.rankList = this.appOptions.Ranks;

                if (this.appOptions.User != null) {
                    this.userRank = this.appOptions.User.RankID;
                    this.userPlatoon = this.appOptions.User.PlatoonID;
                }
            }
            ),
            (err: any) => { // on error
                console.log(err);
            },
            () => { // on completion 

                this.sortRanks();
                this.sortPlatoons();
            }
    }


    // SORT RANK FUNCTION  **************** 
    sortRanks(): void {

        // sort rank list
        this.rankList.sort((b1: Rank, b2: Rank): number => {
            if (b1.Priority < b2.Priority) { return -1; };
            if (b1.Priority > b2.Priority) { return 1; };
            return 0;
        });

        // assign existing rank
        this.selectedRank = this.rankList.filter(function (r) { return r.Code === this.userRank })[0].RankID
    }

    // SORT PLATOONS FUNCTION   ***********
    sortPlatoons(): void {
        // sort results
        this.ptnList.sort((p1: Platoon, p2: Platoon): number => {
            if (p1.PlatoonID < p2.PlatoonID) { return -1; };
            if (p1.PlatoonID > p2.PlatoonID) { return 1; };
            return 0;
        });

        // assign existing platoon
        this.selectedPlatoon = this.ptnList.filter(function (p) { return p.Code === this.userPlatoon })[0].PlatoonID;
    }

}

The mentioned error occurs specifically in the following two lines:

this.selectedRank = this.rankList.filter(function (r) { return r.Code === this.userRank })[0].RankID;

and

this.selectedPlatoon = this.ptnList.filter(function (p) { return p.Code === this.userPlatoon })[0].PlatoonID;

No alterations were made to the code, and none of the other components sharing similar code patterns produce this particular error. Any insights or assistance in identifying why this error surfaces during the CLI build process would be greatly appreciated.

Many thanks in advance for your help!

Answer №1

this.ptnList.filter((p)=> { ..

should be

this.ptnList.filter((p)=> { ..

and the same for

this.rankList.filter((r)=> { 

should be

this.rankList.filter((r)=> {

If you use function, this will refer to that callbacks instance

Suggested reading: How to access the correct `this` inside a callback?

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

A guide on exporting table data to PDF and enabling printing features in Angular 7

Can anyone provide guidance on how to export my dynamic table data into Excel, PDF, and for printing using the appropriate Angular Material components and npm plugins? I have successfully exported the data as an Excel file, but am struggling with exporti ...

Dynamic Angular form with nested elements

Need help creating a nested form following the example from angular.io documentation: https://stackblitz.com/angular/pbdkbbnmrdg The objective is to include two DropdownQuestion elements from question.service.ts within a child formgroup called "details", ...

Angular 2 – Reacting to Dual BehaviorSubjects and Observables

Imagine having a component that requires two observables in order to display its content: this.manifest.subscribe((a) => { f(a, b) }) this.route.params.subscribe((b) => { f(a, b) }) What is the correct Angular and rxjs approach to calling ...

Nextjs provides separate instances for middleware and api routes, even when using the same singleton class

Here is a utility function that acts as a singleton class to store a counter value. export class CounterSingleton { private static instance: CounterSingleton; private count: number; private constructor() { this.count = 0; } public static ge ...

What is the best way to update the value of an input in a child component?

I have two files named person-input.ts and person-input.html What I want to achieve is that when inside the AddPerson function in person-input.ts, I would like to dynamically modify the name-input component by setting [focused]="true" So, the code needs ...

tips for excluding a zustand slice from the blacklist to stop it from persisting

After transitioning from Redux to Zustand for my state management in a new project, I'm facing the challenge of replicating the functionality of Redux-Persist which allows selective persistence in localStorage. I want to apply the blacklist feature fr ...

Retrieve the information from the router link

I have a question regarding accessing the value passed through a routerlink in an anchor tag. How can I achieve this? https://i.stack.imgur.com/Qf500.png In the screenshot above, you can see that "bob" is the data being passed to the component when the a ...

Acquire npm package versions by utilizing the jFrog REST API

Currently, I am attempting to retrieve the versions of an NPM package that has been published on jFrog artifactory. I know how to achieve this using a similar method with the NPM registry through the following URL: https://registry.npmjs.org/lodash Unfor ...

Ensuring robust type safety when using various maps and multiple enums as their keys

I am working on creating a type-safe function for retrieving values from a map. The function needs to handle specific logic in my use case, which is why I require it beyond this simple example below: enum ExampleA { A = 'A' } enum ExampleB { ...

How can I pass custom QueryParams to Router's NavigationExtras in Angular and create a personalized navigation experience?

I am currently working on implementing data filtering functionality in my Angular application. The concept is fairly simple - the user selects filters from dropdown menus and then clicks a button to add key-value pairs of filters to the URL route. There a ...

Cease the RxJS HTTP Polling upon receiving a successful HTTP response

In my code, I have implemented a polling mechanism to mimic HTTP Requests. The goal is to stop sending requests if the server responds with data.length > 0. timeout:Observable<number> = timer(10000); startPollingStackblitz(arnId: string) { ...

`Warning: The alert function is not working properly in the console error

I am currently working on integrating otp functionality into my Ionic 3 project. I am facing an issue where I am able to receive the otp, but it is not redirecting to the otp receive page due to a specific error. Below is the console error that I am encou ...

WebStorm lacks support for TypeScript's `enum` and `readonly` features

When working with TypeScript in WebStorm, I encountered an issue where the IDE does not recognize enum or readonly. To solve this problem, I delved into TypeScript configuration files. I am currently utilizing .eslintignore, .eslintrc, tsconfig.json, and ...

Ways to keep information hidden from users until they actively search for it

Currently, I have a custom filter search box that is functioning correctly. However, I want to modify it so that the data is hidden from the user until they perform a search. Can you provide any suggestions on how to achieve this? Below is the code I am u ...

Angular 2: Converting JSON data into an array

I am working with JSON data that contains vendor fields and I need to extract unique vendors into an array. Can someone provide guidance on how to achieve this in an Angular2 component? Here is the sample data: [{"category": "Living Room", "vendor": "Fle ...

Posting an Angular 6 form to open in a separate tab

I have been exploring ways to set a target on a form within Angular. My goal is to have the submission of the form occur in a new tab, so I tried using the code below: <form id="formLanding" role="form" (ngSubmit)="onSubmit()" #landingForm="ngForm" [ta ...

Return to the previous URL

I am currently facing an issue where I want to go back to the parent URL when a specific option is changed and there are additional route parameters, but maintain the current URL if there are no route parameters. To better illustrate this problem, let me ...

When working with a composite object in React, the state may reset unexpectedly

Just getting started with React and have a question about structuring my app: I'm creating a Book class that has a title and content, both as strings. I want to organize the book page into different components: a BookComponent for the view, a Book ho ...

What is the solution to the problem of a missing property in a TypeScript or Firestore project?

Here is a snippet of code from my TypeScript project: admin.firestore().collection('posts').doc(postId).get().then((data) => { let likesCount = data.data()?.likesCount || 0; let likes = data.data()?.likes || []; let u ...

Creating Typescript: Defining the Type of Object Key for a Generic Type

I've created a custom hook with a generic type to define the return type of the hook. Below is an example of the code I wrote for this custom hook: type Return<T> = [T, (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void, ...