Failed to retrieve information from the Service for the component

My goal is to retrieve data from a service and display it in a component. Below is the code for my service:

Service.ts

export class PrjService {
  tDate: Observable<filModel[]>;
  prjData:Observable<filModel[]>;
entityUrl;
constructor(){
this.entityUrl = 'PrjDetail/GetByRep';
    this.tDate = service.get<ShipDateFilterModel[]>(this.entityUrl);
}

Below is the component where I attempt to fetch and process the data:

export class RFComponent implements OnInit {
  cachedResults: any[];
  shipToData: any;

constructor(private psService: PrjService)
{}
  ngOnInit() {
     this.psService.tDate.subscribe(x => this.cachedResults = x);
     this.filterData = [...new Set(this.cachedResults.map(item => item.cus_name))].filter(Boolean);
  }

However, when the service call is made, this.cachedResults is undefined and I encounter an error when trying to filter:

ERROR TypeError: Cannot read property 'map' of undefined

I am unsure of what I might be missing here.

Answer №1

When you make an asynchronous call, the filteredData statement may not have the cachedResults value fetched from the service yet. This can result in an undefined error.

To address this issue, ensure that the statement is executed only after the service call has been completed and data has been returned as a response.

 ngOnInit() {
     this.psService.tDate
     .subscribe(x => {
        this.cachedResults = x;
        this.filterData = [...new Set(this.cachedResults.map(item => item.cus_name))].filter(Boolean);
     });
  }

Alternatively, you can use the finally method of the Observable object.

 ngOnInit() {
        this.psService.tDate
        .finally(() => {
             this.filterData = [...new Set(this.cachedResults.map(item => item.cus_name))].filter(Boolean);
         })
        .subscribe(x => {
           this.cachedResults = x;
        });
    }

In this approach, the finally method will be called after the observable completes or encounters an error.

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

JavaScript function that outputs a value of 0

I am currently working on developing a route for a node app, where I'm trying to implement a function that calculates the total of all orders at a specific location. While I can successfully log the correct values within the map function (line 12 + 13 ...

Attempting to render a string in React is causing an error because the type 'void | undefined' is not compatible with the type 'ReactNode'

I have developed a custom hook that retrieves an array of objects called navMenuOptions, along with a function that can return a specific navMenuOption based on a string input. export const useNavMenuOptions = () => { const intl = useIntl() const p ...

When viewing a React data table in Chromium browsers, the columns on the right side may flicker when the screen is small or the browser

I recently integrated the React data grid Npm package by adazzle. You can find more information about it here. I encountered an issue which you can see in this example: https://codesandbox.io/s/react-data-grid-example-9sb93?file=/src/App.tsx When using a ...

Evaluating the functionality of Express Js Server with mocha and chai

I'm currently struggling to properly close the server connection in my Express server when testing it with Mocha and Chai. It seems that even after the test is completed, the server connection remains open and hangs. Index.js const express = require( ...

AngularJS directive failing to trigger event binding within the link function

Here is a plunker that you can refer to. In my project, I have developed two simple element directives, named incButtonOne and incButtonTwo. These directives are designed to track and display the number of times they have been clicked. Each directive has ...

What causes getBoundingClientRect() in Javascript to occasionally produce decimal values?

Currently, I am experimenting with an HTML5 canvas element. A major concern of mine is setting up a mousemove event to monitor the movement of the mouse over the canvas for drawing and other purposes. Unfortunately, I have not been able to locate a definit ...

Invoking a method in Vue.js from another component

I'm just starting out with VUE and I have a unique challenge for my project. I want to have a button on one page that triggers a function on another page. I know some may ask why not keep the button and function on the same page, but I am exploring ho ...

When using React, my goal is to preserve state even after the page is refreshed

I am facing an issue in React where I want to persist state even after refreshing the page. I attempted to use localStorage, but every time the page is refreshed, the data gets cleared. function App() { const [selected, setSelected] = useState() con ...

Looking for assistance with ReactJs code related to implementing a filter button

I've been working on creating a filter button using ReactJs, but I can't seem to get it to work properly. I've spent a lot of time troubleshooting, but the issue persists. You can view my codePen here: https://codepen.io/tinproht123/pen/gOxe ...

What is the optimal method for sending search criteria to the server using AJAX?

Take a look at the HTML snippet below: <input type='text' id='name'/> <option id='option'> <select value='1'>hi</select> <select value='2'>bye</select> </option&g ...

Binding data to custom components in Angular allows for a more flexible

In my current scenario, I am looking to pass a portion of a complex object to an Angular component. <app-component [set]="data.set"></app-component> I want the 'data.set' object in the parent class to always mirror the 'set&apo ...

Tips for circumventing debounceTime in Angular

In my current setup, I am utilizing a text input along with a debounceTime pipe to ensure that server requests are not made too frequently while the user is typing: this.keyUp$ .pipe(debounceTime(500)) .subscribe(data => this.onInputChanged.emit ...

Is there a way to determine if a certain class link within a DIV has been clicked and then replace the DIV's click functionality?

I have multiple DIV elements like the one below on my webpage: <div class='entry'> This is a statement <a title="Search @travel" class="app-context-link" href="">@travel</a> </div> When a DIV with the class .ent ...

Leveraging Angular Dragula without the need for RequireJS

I'm eager to incorporate Drag and Drop functionality into my Angular project with the help of the angular-dragula module (https://github.com/bevacqua/angular-dragula). However, it appears that this module heavily relies on RequireJS. My experience wit ...

Navigate to component depending on an external query parameter in Angular 2

Is there a way to set up my router so that it redirects based on a specific query string? Let's consider this scenario: the application sends an email for code validation, and I want the user to be directed to a specific component when they click on t ...

Adjusting the size of an HTML5 canvas using a class function when a resize event occurs

I'm attempting to adjust the size of a canvas element using a resizeCanvas() method triggered by a resize event. When I directly call the method, the canvas resizes without any issues. However, when the event handler triggers subsequent calls, I encou ...

Using more than one class at a time is causing issues

Essentially, I have a div and I want to create an exercise where I apply three different classes using vue.js. I attempted to use v-bind:class, specifically :class, but can I bind a class directly from CSS? This is what I tried: html <div :style="[my ...

Using AngularJS to bind a model within ng-repeat in a custom directive

Currently, I am attempting to bind a model from inside an ng-repeat within a directive to the outer controller. In the outer controller, there is a variable that I would like to bind, as shown below: //in the directive scope filterArray: '=' ...

Receiving a form submission via POST method from an external source without redirection

Situation: A user visits site A and submits a form with a hidden input field containing base64 encoded data. The action leads to site B, which is an Angular 2 application. The structure of the form is as follows: <form id="partner" method="POST" actio ...

Creating a Star Rating System Using HTML and CSS

Looking for help with implementing a Star rating Feedback on articles in Visualforce page. Came across some code that seems to fit the bill but facing issues with getting it to work when placed in a file and executed, particularly in Firefox. Any assistanc ...