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

Update constant data returned from Angular2 service

Issue at Hand: I am facing an issue where I want to store default data in a separate file so that I can easily reset the default value when needed. However, the Const Data seems to be getting updated. I could simply hardcode the value directly into the co ...

The object literal is restricted to defining existing properties, and 'id' is not a recognized property in the type 'FindOptionsWhere<Teacher>'

I encountered a persistent error within my teachers.service: Object literal may only specify known properties, and 'id' does not exist in type 'FindOptionsWhere | FindOptionsWhere[]'.ts(2353) FindOneOptions.d.ts(23, 5): The expected t ...

Leveraging npm for the development of my TypeScript/Node.js project

I'm facing challenges working on a project written in TypeScript and running on Node. I am finding it difficult to write the npm script to get it up and running properly for development purposes. What I am attempting to achieve is: clear the /dist f ...

Preventing parent requests from being triggered when a child element is clicked in Angular 2

I have a similar code structure as shown below and I am trying to achieve the behavior where clicking on the Child Div does not trigger the Parent Div click event. <div class="parentDiv" (click)="parentDiv()"> <div class="childDiv" (click)="ch ...

What is the reason that {a: never} is not the same as never?

Is there a reason the code {a: never} cannot be simplified to just never? I believe this change would resolve the issues mentioned below. type A = {tag: 'A', value: number} type B = {tag: 'B', value: boolean} type N = {tag: never, valu ...

Execution issue with Typescript function

In my Nativescript project, I have the following TypeScript file: import { Observable } from 'tns-core-modules/data/observable'; import { isIOS } from "tns-core-modules/platform"; import { Color } from "tns-core-modules/color"; import { request, ...

What could be causing my TypeScript code to not be recognized as CommonJS?

I rely on a dependency that is transpiled to ES6. My goal is to leverage ES2019 features in my own code. Ultimately, I aim to output ES6. This is how I set up my tsconfig { "compilerOptions": { "module": "CommonJS" ...

What is the consensus on incorporating client-side routing in conjunction with the server-side routing features offered by angular-universal

I am diving into the world of Angular Universal and exploring 'isomorphic' javascript for the first time. I am a bit puzzled about how to set up a logical routing system. Should I treat Angular Universal as a typical Node.js REST API? Or is its ...

An issue arises with launching karma.js when importing node-openid-client in a TypeScript specification file

Utilizing the node-openid-client library for OpenIDConnect based authentication with an OpenID Provider. Encountering challenges while attempting to write test cases for the program. The application runs smoothly from node CLI, obtaining the code and toke ...

Tips on applying the "activate" class to a Bootstrap navbar in Angular 2 when implementing page anchor navigation

As I work on my single-page website using Angular 2 and Bootstrap 4, I have successfully implemented a fixed navbar component that remains at the top of the page. Utilizing anchor navigation (#id), the navbar allows smooth scrolling to different sections o ...

How come a null variable continues to widen to type any even when strictNullChecks is enabled?

According to the TypeScript Documentation, if strictNullChecks is true, there should be no type widening. Also, the typeof nul should be null. let nul = null; // typeof nul = any let undef = undefined; // typeof undef = any Check it out in the Playground ...

The combination of TypeScript output is not working as expected

Here is my current configuration: tsconfig.json { "compileOnSave": true, "compilerOptions": { "module": "none", "outFile": "js/app.js" } } MyApp.Main.ts class Main { constructor() { Utilities.init(this); ...

Discovering the ASP.NET Core HTTP response header in an Angular application using an HTTP interceptor

I attempted to create a straightforward app version check system by sending the current server version to the client in the HTTP header. If there's a newer version available, it should trigger a notification for the user to reload the application. Ini ...

What is the process for including an object in an http.post request?

My contact object needs to be included in the http.post method. I'm struggling with where exactly to pass this contact parameter. Can you provide guidance on how to modify my code accordingly and also share any relevant links related to the http.post ...

The element is automatically assigned an 'any' type due to the fact that a 'string' expression cannot be utilized to index the type 'typeof'

I am facing an issue that I am having trouble understanding. The error message reads as follows: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof The proble ...

Exploring the differences in object shapes using TypeScript

I'm currently working on defining an object that has the ability to hold either data or an error. export type ResultContainer = { data: any; } | { error: any; }; function exampleFunction():ResultContainer { return { data: 3 } } ...

Determine whether the ng bootstrap modal has already been opened

Is there a way to determine if a modal window is open? In order to accomplish this, I create a variable called modalInstance: NgbModalRef; and initialize the modal by using the code below this.modalInstance = this.modalService.open(UpdateModalConten ...

Validation of Forms and Displaying Error Messages in Angular 7

Please take a look at my straightforward form on Stackblitz https://stackblitz.com/edit/angular-et9uww Within my form, there are 2 checkboxes. When one checkbox is selected, it will populate a corresponding textbox. In this particular scenario, there are ...

The input field in iOS is shielded by the keyboard on Ionic 5

For months now, I've been struggling with the same issue and I just can't seem to find a solution. The problem arises in an application where there are multiple forms; when a user focuses on an input field, the keyboard covers it up completely ma ...

What are some alternatives to using multiple slot transclution in an Angular 1.5 component?

In the process of constructing a panel component using angular 1.5, I am looking to embed some markup into this template (which has been simplified): <div class="panel"> <h1>{{ $ctrl.title }}</h1> <div ng-transclu ...