Showing data related to a certain value - what's the best way?

I am currently working on a page where I need to display and edit specific user information at /users/524.json. However, I also want to include the working days from another table on the same page. I have provided most of the code below for reference. Unfortunately, I am unable to deploy it on "StackBlitz" at this time. The main issue seems to be with the " loadWorkingDays" function. Could you please take a look and advise on what needs to be fixed?

HTML:

<div class="card">
  <table>
    <thead>
      <tr>
        <th>Working Days</th>
      </tr>
     </thead>
     <tbody>
       <tr *ngFor="let workingDay of filteredWorkingDays" >
          <td>{{workingDay.date}}</td>                             
       </tr>
      </tbody>
   </table>
</div>

TS:

  
  ...
  users: Array<User>;
  workingDays: Array<WorkingDay>;
  id: number;
  routeId: any;
  returnUrl: string;
  public errorMsg;
  filteredWorkingDays = [];

  constructor(
    private authTokenService: Angular2TokenService, 
    private route: ActivatedRoute,
    private router: Router,
    private servUser: UserService,
    private servWorkingDay: WorkingDayService,
  ) {
    this.workingDays = new Array<WorkingDay>();
    this.users = new Array<User>();
  }

  @Input() workingDay: WorkingDay;
  @Input() user: User;

  ngOnInit() {
    this.loadWorkingDays();
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/users';
    this.routeId = this.route.params.subscribe(
      params => {
        this.id = +params['id'];
      }
    )
    let userRequest = this.route.params
      .flatMap((params: Params) =>
        this.servUser.getUser(+params['id']));
    userRequest.subscribe(response => this.user = response.json(), error => this.errorMsg = error);
  }

  private loadWorkingDays() {
        let filteredWorkingDays = this.workingDays;
        if (this.servWorkingDay) {
          this.servWorkingDay.getWorkingDays().subscribe(workingDay => this.workingDays = workingDay);
            }
        this.filteredWorkingDays = this.workingDays.filter((workingDay) => workingDay.w_user_id == this.user.user_id);

      }
 ...

Answer №1

The issue lies in this particular section of code:

this.filteredWorkingDays = this.workingDays.filter((workingDay) => workingDay.w_user_id == this.user.user_id);

It is crucial that this line also resides within the subscribe callback. Otherwise, filteredWorkingDays will remain undefined as workingDays is not yet defined when assigned.

Your revised function should appear as follows:

private loadWorkingDays() {
    let filteredWorkingDays;
    if (this.servWorkingDay) {
        this.servWorkingDay.getWorkingDays().subscribe(workingDay => {
            this.workingDays = workingDay;
            this.filteredWorkingDays = this.workingDays.filter((workingDay) => workingDay.w_user_id == this.user.user_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

What is the proper way to link a component so that it refreshes whenever a value is modified?

Currently, I have developed a basic application that is designed to retrieve the current weather information for a specific location. By default, this application sets a particular location but offers buttons in one of its components for users to change th ...

Managing errors with async/await in an Angular HttpClient function

I have been experimenting with an async/await pattern to manage a complex scenario that could potentially result in "callback hell" if approached differently. Below is a simplified version of the code. The actual implementation involves approximately 5 co ...

Forward user to a subdomain once they have successfully logged in on an Angular 2 application

I've been working on an Angular 2 application and I'm looking to redirect users from www.example.com to admin.example.com after they successfully log in. What is the best way to accomplish this using Angular 2? Additionally, how can I test this f ...

What is the reason behind Angular's utilization of rxjs fromEvent in the type ahead example (debounce) instead of Renderer2.listen?

The Practical Observables section of the Angular manual showcases the use of debounce in a type-ahead scenario, as seen in this excerpt: const typeahead = fromEvent(searchBox, 'input').pipe( map((e: KeyboardEvent) => e.target.value), filt ...

How can I create an interceptor in Angular2 to detect 500 and 404 errors in my app.ts file?

Creating an Angular2 Interceptor for Handling 500 and 404 Errors in app.ts In my app.ts file, I am looking to implement an interceptor that can detect a 500 or 404 error so that I can appropriately redirect to my HTML 404 or HTML 500 pages. Is this funct ...

Having trouble with ESLint in VSCode? The ESLint extension seems to be ignoring linting rules after starting a new project within VSCode

I recently started using the ESLint extension in my VSCode editor for my React project. After creating the starter files, I ran the following command in my terminal: eslint --init This allowed me to choose the AirBnb style guide with React, which generat ...

What is the best way to implement a custom NgbDateParserFormatter from angular-bootstrap in Angular 8?

Currently, I am working on customizing the appearance of dates in a form using Angular-Bootstrap's datepicker with NgbDateParserFormatter. The details can be found at here. My goal is to display the date in the format of year-month-day in the form fi ...

"The latest version of Angular, version 15, experiencing issues with javascript loading

Currently, I am diving into the world of Angular and encountering a puzzling dilemma. Surprisingly, my application performs flawlessly on various browsers such as Chrome, Firefox, Brave, Opera, and even on mobile versions except for Safari. Both the deskto ...

Error: Unable to load the parser '@typescript-eslint/parser' as specified in the configuration file '.eslintrc.json' for eslint-config-next/core-web-vitals

When starting a new Next.js application with the specific configuration below: ✔ What name do you want to give your project? … app ✔ Do you want to use TypeScript? … No / [Yes] ✔ Do you want to use ESLint? … No / [Yes] ✔ Do you want to use T ...

Encountering an error when attempting to iterate over an undefined property using an API

I am trying to fetch all classes and their assignments from Google Classroom. I successfully used Google's example code for listing the classes, but had to write my own code for listing the assignments. While the code runs as expected and lists the as ...

Displaying data from multiple checkboxes in an Angular application using an array

I'm currently facing an issue with displaying checked data in an Array within my Angular application. Upon clicking the checkbox, I receive a true value, but unfortunately, the data does not display as it contains null values. For reference, here is ...

Issue with ambient contexts error in TypeScript constructor

What is the correct way to create a constructor in TypeScript? I have been researching and trying different approaches, but it seems like the syntax has changed. Here is my latest attempt: car.d.ts declare class Car { constructor(public engine: string ...

npm-bundle encounters an issue with Error: ENOENT when it cannot find the file or directory specified as 'package.json'

npm-bundle is throwing an error that says Error: ENOENT: no such file or directory, open 'package.json' in my NodeJs project. It works fine if I manually create test.js and package.json, then run npm install followed by npm-bundle. However, when ...

"Exploring the process of accessing the request headers section within the network tab of your browser

How can I extract the access date from the request headers section in the network tab of my browser when receiving a response from the API? Can someone help me with this problem? ...

Can fields from one type be combined with those of another type?

Is it possible to achieve a similar outcome as shown below? type Info = { category: string } type Product = { code: string, ...Info } Resulting in the following structure for Product: type Product = { code: string, category : string } ...

Is there a way to restrict the return type of a function property depending on the boolean value of another property?

I'm interested in creating a structure similar to IA<T> as shown below: interface IA<T> { f: () => T | number; x: boolean } However, I want f to return a number when x is true, and a T when x is false. Is this feasible? My attempt ...

Ending the Infinite Scroll in Ionic 3 When Data Runs Out

I am having an issue with my json data where I need to figure out how to stop the infinite scroll once there is no more data available. Can anyone help me implement this feature? Below is the code snippet for reference: handleDataLoad(currentCount) ...

Using TypeScript to pass an object's method as an argument in a function call

Recently, I delved into game development using cocos creator with TypeScript/JavaScript, languages that are still new to me. My current challenge involves creating a complex callback method that will trigger methods attached to an array of objects. Here&a ...

Exploring the world of Wordpress Rest API for retrieving posts

I'm attempting to display all of my posts from my WordPress website. Currently, there are 2 posts available which can be viewed in the JSON file: View export class HomePage { url: string = ‘http://feederhorgasz.000webhostapp.com/wp-json/wp/v2/posts ...

Guide on integrating an element into a different element in a Vue 3 Tree Viewer

In my current setup, I've implemented a TreeView component that holds a tree. Each tree entry includes Children with their own unique label, perm, and further children. Take a look at an example of the tree: App.vue let tree = ref({ label: 'o ...