The issue arises when trying to use data provided by a service, resulting in an "undefined

Looking to create a handler that generates an array of categories based on the presence of "categories" for a specific "resource". However, encountering an error with the last method. ERROR TypeError: "this.allProjectResources is undefined"

import { ResourceCategory } from './resourceCategory';
import { Injectable } from '@angular/core';
import { Resource } from './resource';
import { HttpService } from '../project/http.service';
import { isNullOrUndefined } from 'util';

@Injectable()
export class ResourceService {

    public allProjectResources: Resource[];
    public allResourceCategories: ResourceCategory[];

    uniqueResCategories = new Set();

    constructor(private http: HttpService) { }

    getAllResourcesByProjId(projid: number) {
        if (!(isNullOrUndefined(this.allProjectResources))) {
            this.allProjectResources.length = 0;
        }
        this.http.getAllResourcesById(projid).subscribe((data: Resource[]) => 
        this.allProjectResources = data);
    }
    getAllResourceCategories() {
        this.http.getAllResourceCategories().subscribe((data: ResourceCategory[]) =>
        this.allResourceCategories = data);

    }
    getAllUniqieResourceCategories(){
        this.allProjectResources.forEach(resource => {
            this.allResourceCategories.forEach(function (category) {
                if (resource.resourceCategoryId == category.id) {
                    this.uniqueResCategories.add(category.name);
                    console.log(category.name);
                };
            });
        });
    }
}

Answer №1

Set class variables to an empty array initially

public allProjectResources: Resource[] = [];
public allResourceCategories: ResourceCategory[] = [];

In addition, make sure to assign an empty array in the getAllResourcesByProjId() method instead of changing the length property directly

getAllResourcesByProjId(projid: number) {
        if (!(isNullOrUndefined(this.allProjectResources))) {
           // this.allProjectResources.length = 0;
            this.allProjectResources = [];
        }
        ...
}

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 best way to properly redirect a page using a router link in Vue.js 2?

I've encountered an issue with the router-link component in Vue.js 2. I have set up my router file index.js import Vue from 'vue'; import VueRouter from 'vue-router'; import HomeView from '../views/HomeView.vue'; import ...

What is the process for updating the authService in Angular to return an observable using the map function from the previous version?

I recently followed a tutorial on JWT authentication with ASP.NET Core 2 Web API, Angular 5, .NET Core Identity, and Facebook login. The tutorial can be found here. While the tutorial was well-written, it utilized an older version of Angular (I am using An ...

Obtain the content of every cell in a constantly updating table

I have created a dynamic table as shown below: <table id="sort" class="table"> <thead> <tr> <th>Column Name from DB*</th> <th>Record Le ...

How is it that the chosen attribute functions for every ng-container?

I have 2 ng-containers. When I am in one view, I want "My Appointments" selected in the options dropdown when navigating to that view. In the other view, I want "Active" selected in the options dropdown. Here is my html code: <div class="wrapper w ...

The specified type '{}' cannot be assigned to type 'ReactNode'

Can someone help me figure out why I am getting this error in Vercel but not locally? Error: 'FontAwesomeIcon' cannot be used as a JSX component. ./components/Services/ServiceContainer.tsx:25:6 12:01:54.967 Type error: 'FontAwesomeIcon&a ...

Having trouble integrating Backbone-relational with AMD (RequireJS)?

I'm struggling with my Backbone router and module definitions in CoffeeScript. Can someone help me troubleshoot? // appointments_router.js.coffee define ["app", "appointment"], (App) -> class Snip.Routers.AppointmentsRouter extends Backbone.Rout ...

Manipulating global state properties within a reducer function in React: How to do it efficiently

I am looking to implement a single loader (backdrop and spinner) within my app component that can be displayed based on the value of a property in the Redux state called showLoader. This loader should be accessible throughout my entire React application. T ...

Unable to modify preset choices in radio checkboxes

I am a paramedic with no prior experience in this area. My task involves completing numerous patient forms that contain excessive fields, creating redundancy. To streamline this process, I am attempting to script a solution that will automatically populat ...

IE does not render the output of multiple AJAX requests

Desiring an autocomplete feature for an input box that displays results in a div below it, I wrote this shortened code. It functions flawlessly on Chrome and Firefox - when searching for "Eggs" and then "Milk", their respective results appear. However, Int ...

Transform a collection of interfaces consisting of key-value pairs into a unified mapped type

I have a set of interfaces that describe key-value pairs: interface Foo { key: "fooKeyType", value: "fooValueType", } interface Bar { key: "barKeyType", value: "barValueType", } interface Baz { key: "bazKeyType", value: "bazValue ...

The combination of jQuery, using .load method in javascript to prevent scrolling up, making XMLHttpRequest requests, updating .innerHTML elements, and troubleshooting CSS/JS

While utilizing this code, CSS and Javascript are disabled (only HTML loads): function loadContent(limit) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status ...

What is the comparable javascript code for the <script src="something1.json"></script> tag?

Within my HTML code, I currently have the following line to read a JSON file: <script src="something1.json"></script> Inside this JSON file, there is a structure like so: var varName = { .... } This method of definition naturally sets up ...

Dynamic HTML5 elements in constant motion

I'm interested in creating an HTML5 canvas that features bouncing circle and square elements that interact with each other, potentially spinning upon collision. The best example I've come across so far is located at this link. var canvas = docu ...

Accurate TS declaration for combining fields into one mapping

I have a data structure called AccountDefinition which is structured like this: something: { type: 'client', parameters: { foo: 3 } }, other: { type: 'user', parameters: { bar: 3 } }, ... The TypeScript declaration ...

Updating certain fields in AngularJS with fresh data

I am facing a challenge with the following code snippet: <div ng-controller="postsController"> <div id = "post_id_{{post.postid}}" class = "post" ng-repeat="post in posts"> ...... <div class="comments"> < ...

I am encountering an issue where the POST data is not being successfully sent using XMLHttpRequest unless I include

I have a unique website where users can input a cost code, which is then submitted and POSTed to a page called 'process-cost-code.php'. This page performs basic validation checks and saves the information to a database if everything is correct. T ...

The null object does not have a property addEvenListener and therefore cannot be

My goal is to develop a simple single-page application without using any frameworks, focusing on providing users with tutorials on specific subjects. I am encountering an issue with the javascript code for my page, receiving the following error: Uncaug ...

Error encountered: The combination of NextJS and Mongoose is causing a TypeError where it is unable to read properties of undefined, specifically when trying

Versions: Next.js 14.1 React 18 I am currently developing a profile section where users can update their profile information such as username, name, and profile photo. To achieve this, I have implemented a component that contains a form (using shadcn) to ...

Managing file sizes on the client side prior to transferring them to the server side

I am looking to implement client-side validation for file size. The current code only handles success, but I also want to address file size limitations. Right now, if a file exceeds 2MB, it results in a 500 (Internal Server Error) behind the scenes. Is th ...

Having trouble with Angular ngRoute functionality?

I'm currently working on configuring a basic Angular app. Here is my main HTML: <html ng-app="CostumerApp"> <head> <title> Customers </title> <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstr ...