The function does not yield any result

import { Injectable } from '@angular/core';

export class Test {
  public id: number; public name: string; public fid: number
};

export const TESTS2: Test[] = [
  {id: 1, name: 'Lion', fid: 1},
  {id: 2, name: 'Tiger', fid: 1},
  {id: 3, name: 'Bear', fid: 1},
  {id: 4, name: 'Wolf', fid: 1},
  {id: 5, name: 'Fox', fid: 2},
  {id: 6, name: 'Panda', fid: 2},
  {id: 7, name: 'Kangaroo', fid: 2},
  {id: 8, name: 'Giraffe', fid: 2},
  {id: 9, name: 'Zebra', fid: 3},
  {id: 10, name: 'Horse', fid: 3},
  {id: 11, name: 'Llama', fid: 3},
  {id: 12, name: 'Squirrel', fid: 3}];

let testsPromise2 = Promise.resolve(TESTS2);

@Injectable()
export class TestService2 {
  getTests(id) { 
    let items: Test[] = [];
    for(var i = 0; i < TESTS2.length; i++) {
        if(TESTS2[i].fid == id) { 
        items.push(TESTS2[i]) 
        }
    }
    return testsPromise2;
 }
}

I am encountering an issue where TESTS is not accessible within the getTests function, however, testsPromise can be accessed as I receive all data if I return testsPromise in the getTests function. Why is this happening?

Answer №1

Make sure to start by initializing your items:

  let itemList: Item[] = [];

Answer №2

Can Test be considered an interface in this scenario?

interface Test {
    id: number;
    name: string;
    fid: number;
}

If that is the case, ensure to initialize the items array before starting the loop (using let):

getTests(id: number) {
    let items: Test[] = [];
    // ...
}

Also, confirm that the declaration of TESTS is accessible within the function:

getTests(id: number) {
    console.log(TESTS); // can you see this output?
    // ...
}

By following the steps above, your code should function correctly.


As a bonus tip, for further optimization, consider rephrasing your function into a single line:

getTests(id: number): Test[] {
    return TESTS.filter((oneTest: Test) => oneTest.fid === id);
}

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

Can you explain how to incorporate global functions from a javascript library into an Angular 2 project?

Recently I started working with angular-cli and came across a situation where I have an index.html containing a javascript script with some global functions. I want to access these functions in multiple parts of my application. As someone who is new to A ...

The Splitter remains inactive until a peculiar series of actions is taken

Trying to troubleshoot this issue with a library called Split.js, which can be found here: https://github.com/nathancahill/Split.js I've encountered an interesting problem where I have to disable the height CSS property of my container, move the spli ...

The Javascript function must be executed with each page reload

Currently, I am analyzing an asp.net 2 web application that is in my care (even though I did not create it). There seems to be an issue with certain functionalities not working consistently when the page loads, particularly if using Firefox 3 within a vir ...

Transform the process.env into <any> type using TypeScript

Need help with handling logging statements: log.info('docker.r2g run routine is waiting for exit signal from the user. The container id is:', chalk.bold(process.env.r2g_container_id)); log.info('to inspect the container, use:', chalk.b ...

When the application is converted into static files, the dynamic routes fail to function properly

I have a website that is statically exported but has dynamic routes. During development, the site works fine. However, when I build and export it, then serve the static files using serve, an issue arises. If you go to the site root and click on a link th ...

Unlocking $refs with the Composition API in Vue3 - A step-by-step guide

I am currently exploring how to access $refs in Vue 3 using the Composition API. In my template, I have two child components and I specifically need to obtain a reference to one of them: <template> <comp-foo /> <comp-bar ref="ta ...

The function successfully triggers when clicked using (React, JS, TS) but does not respond to key presses

When the function is called with "onClick", it works correctly, but when called with "onKeyPress", it does not execute an if statement. scenario Consider a scenario where you can search for food recipes (e.g. "pizza") and receive a list of recipes from a ...

Is there a way for me to access the source code of elements within React Native?

Currently, I am working on writing code using React Native and compiling it in Android Studio with an emulator. When I press ctrl+m on the emulator and select "show inspector" to click on elements, I am unable to see which line of code corresponds to the s ...

Can file input buttons be custom styled?

Since I am using Material-UI, the traditional methods are not working for me. I have a form with two buttons positioned next to each other. One button is an "Upload File" input for users to upload a file, and the other is a submit button. I want both butto ...

What is the best way to make an element disappear 5 seconds after the mouse has stopped hovering

#section1 { display: block; } #section2 { display: none; } #container:hover > #section2 { display: block; } <div id="container"> <div id="section1">Section1</div> <div id="section2">Section2</div> </div> ...

Typedoc does not create documentation for modules that are imported

Whenever I generate documentation with TypeDoc, I am encountering an issue where imported files come up empty. If I add a class to the file specified in entryPoints, I get documentation for that specific class. However, the imported files show no document ...

Preflight request rejection due to access control check failure in React and Express

I am facing a similar issue to this question, but my problem is specific to using Express with React on the frontend. The error I am encountering is: Access to fetch at 'http://localhost:8000/api/users/auth/github' from origin 'http: ...

How to include a javascript file in a different file and compile it using Node.js

For running my practice JS files, I rely on Node. As an example, I use node bts.js. In order to implement a queue, I decided to install Collections by using the command npm install collections --save. You can also see this reflected in the hierarchy shown ...

Inconsistent Accuracy of React Countdown Timer

Hello everyone! I'm new to programming and I'm currently working on creating a countdown timer that goes from 3 to 0. The issue I'm facing is that the timer counts down too quickly when rendered on the screen. I've tried adjusting the i ...

Error message: "The function platform_browser_dynamic_1.bootstrap does not exist in Angular 2."

I had everything set up and running smoothly until suddenly I started receiving this error out of nowhere: TypeError: platform_browser_dynamic_1.bootstrap is not a function Here's the component I've been working on: import { Component, Input, ...

Extract information from a specific div element and save it to a text file

I'm currently working on extracting data from a div and sending it to a PHP file using the following JavaScript: $(document).ready(function(){ $('#save').on('submit',function(e) { var bufferId = document.getElementById ...

When working with Typescript, NextAuth throws errors while embedding

When attempting to implement NextAuth into my Typescript application, I encounter two errors: one with NextAuth and the other with NextAuthOptions. import NextAuth from "next-auth" import { NextAuthOptions } from "next-auth" import Go ...

Different Types of Forms on a Single Webpage Using AJAX

I'm struggling to get multiple forms to work on the same page. No matter what I try, it always submits the first form. The goal is to identify each form uniquely so that only the specific one is submitted. The current code below achieves this but alw ...

Utilizing Typescript for manipulation of Javascript objects

Currently, I am working on a project using Node.js. Within one of my JavaScript files, I have the following object: function Person { this.name = 'Peter', this.lastname = 'Cesar', this.age = 23 } I am trying to create an instanc ...

A guide on resolving deprecated warnings for typographical errors

Every time I try to npm install I am bombarded with numerous errors. typings WARN deprecated 9/9/2016: "registry:dt/node#6.0.0+20160831021119" is deprecated (updated, replaced or removed) My experiences with typescript have been nothing but a series ...