Acquiring information from a Service and saving it in a Child component - Angular version 11

Utilizing my service, I fetch API data for the child component. Initially, it retrieves the Id and other user data, displaying it in the console.

ngOnInit(): void {
    this.commonService.userSetChange.subscribe(
      apiData => {
        this.getUserSeminar(apiData);
        this.user = apiData;
        console.log(this.user)

      });
  }

Next, I save this data using a variable named user.

user: any;

The following method is used to pass the user variable:

addSeminar(): void {
    console.log(this.user.id)
    event.preventDefault();
    const seminar = {
      id: null,
      user_id: this.user.id,
      dates: null,
      name: null,
      certificate_number: null,
      edit: true,
    };
    this.userSeminars.push(seminar);
    const a = this.userSeminars.length - 1;
  }

However, upon clicking the addSeminar button,

<button class="btn btn-primary btn-sm" (click)="addSeminar()">Add Seminar &nbsp; <i class="fa fa-plus"></i></button>

An error is encountered: api/users/seminar/null 500

https://i.sstatic.net/Tc55C.png

Answer №1

The organization of your code has directly impacted the current situation you find yourself in. The screenshot provided offers a clear explanation. The undefined message is associated with the console.log(this.user.id) within the addSeminar(){} method. The presence of null indicates that no value was sent to the server. However, the initial section of the screenshot displays the id:1, which seems to be the parameter intended for the addSeminar(){} function.

To address this issue, consider moving the addSeminar(){} function inside the subscription block within the ngOnInit(){} function. After receiving data from the API and assigning it to this.user = apiData;, pass the required parameter to the addSeminar() function. If you prefer to keep your functions concise, you can add an argument to

addSeminar(userId: string|number){}
, leave it in its current location, and call it as directed above.

Therefore, your revised logic should resemble the following:

ngOnInit(): void {
    this.commonService.userSetChange.subscribe(
      apiData => {
        this.getUserSeminar(apiData);
        this.user = apiData;
        console.log(this.user)
        this.addSeminar(this.user?.id) // make sure to include this line
      });
  }

PS: It is recommended to avoid using type any whenever possible. Consider using unknown instead.

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

The specified argument, 'void', cannot be assigned to a parameter that expects 'SetStateAction | undefined'

Currently, I am engaged in a TypeScript project where I am fetching data from an endpoint. The issue arises when I attempt to assign the retrieved data to my state variable nft using the useState hook's setNft function. An error is being thrown specif ...

Angular Universal: Dividing projects [A resolution for dated or intricate projects]

Working on an aging Angular project that has been through multiple upgrades since the 2.0 release, we are currently at version 4.3. The project has become quite complex over time, with numerous features and outdated peer dependencies that are no longer be ...

A versatile function catered to handling two distinct interface types within Typescript

Currently, I am developing a React application using TypeScript. In this project, I have implemented two useState objects to indicate if an addon or accessory has been removed from a product for visual purposes. It is important to note that products in thi ...

Dynamically assigning values to class properties in Angular with Typescript is a powerful

I am working on a project where I have a class and a JSON object. My goal is to update the properties in the class based on the values in the JSON object, using Angular 9. This is the class: export class Searchdata{ name:boolean=false; age:boolean=fa ...

The FileReader's onload event handler does not seem to be triggering as expected

In short, my issue revolves around reading a csv file from an android device using JavaScript's FileReader. Although my code was functioning properly a month ago, upon revisiting it recently I discovered that the onload function no longer seems to be ...

Unable to swap out string with text box in TypeScript

I am trying to swap __ with a text box in Angular 2/4. Take a look at the example provided in the link below. https://stackblitz.com/edit/angular-ajkvyq?file=app%2Fapp.component.ts ...

Maximizing Efficiency of Vendor Bundle in Angular 2 with Webpack

My MEAN application's client side is built in Angular2 with Webpack, but I'm facing slow loading times due to a large vendor modules JS file. Is there a way to optimize this situation? I want to separate the vendor's JS file. Below is my we ...

Issue encountered: XHR error (404 Not Found) occurred following the installation of typescript-collection in Angular 2 final version

After setting up an Angular 2 project quickly, I added the typescript-collections package using the command: npm install typescript-collections --save However, upon launching my project, I encountered the following error: GET http://localhost:63342/IMA% ...

What is the method to modify the starting point of the animation for the material component "mat-progress-bar" so it initiates from 0 instead of 100

I recently integrated a material progress bar into my Angular project. Here is the code snippet: <mat-progress-bar mode="determinate" value="40"></mat-progress-bar> However, I encountered an issue where upon page refresh, ...

Experience the power of transforming nested forkjoin operations into observables

Trying to implement a solution in my resolver that involves nested forkjoins and subscribes has been challenging. I attempted using maps, but I still need to fully grasp the concepts of maps/switchMaps/mergeMaps. Even though the code doesn't currently ...

Steps for sending a POST request with data from Ionic 4 to Django Rest Framework

I am attempting to make a post request from my ionic V4 project to the Django backend website. Below is the code I am using: Django Code models.py Here is the class where I need to post data to: class Item(models.Model): (...) serializers.py - thi ...

How does TypeScript interpret the data type 'a' | 'b' as a string?

As a beginner in TypeScript, React, and English, I apologize for any confusion. I have written a function like this: interface ObjectAttrUniqueState { editVisible: boolean; currentId: number; selectedUnique: number[]; name: string; desc: string; ...

Transferring data from a child to a parent component in Angular 2 using a combination of reactive and template-driven approaches

Recently delving into Angular 2 ( and Angular overall ) , I found myself at a crossroads with my co-worker. He opted for the template-driven method while I leaned towards the reactive-driven approach. We both built components, with his being a search produ ...

The global CSS styles in Angular are not being applied to other components as expected

Currently utilizing Angular v10, I have a set of CSS styles that are meant to be used across the entire application. To achieve this, I added them to our global styles.css file. However, I'm encountering an issue where the CSS is not being applied to ...

Incorporate a stylish gradient background into react-chartjs-2

I am currently working on adding a gradient background with some transparency to a radar graph within a react component. So far, I have only found solutions that involve referencing a chartjs canvas in an html file, but none for implementing it directly in ...

Whenever comparing the types 'string[]' and 'DeliveryTypeEnum', this condition will consistently result in 'true' as there is no intersection between the two. This is highlighted by the error code ts(2367)

Hello everyone, I'm a junior developer and could use some assistance if (query.deliveryType && query.deliveryType != DeliveryTypeEnum.EITHER) { search.push({ terms: { "deliveryType.keyword&q ...

Save the application's state of the user in a mean stack program

In my Angular 9 application, I have forms with multiple sections. The first section includes name and personal details, the second part covers primary school information, and the third part focuses on past jobs held by the user. Each part is displayed in a ...

How can I retrieve all element attributes in TypeScript using Protractor?

I came across this solution for fetching all attributes using protractor: Get all element attributes using protractor However, I am working with TypeScript and Angular 6 and struggling to implement the above method. This is what I have tried so far: im ...

Is the tooltip display for Typescript types in VSCode reliable? No need for unnecessary type assertions

Exploring the concept of const assertions in TypeScript Looking at the array allDeviceTypes depicted below, VSCode indicates it has a return type of string[] when hovering over the variable name. https://i.sstatic.net/gIYch.png However, upon using a con ...

What steps can be taken to prioritize files with specific extensions in webpack?

I have a dilemma with two files: - somefile.scss - somefile.scss.ts When importing the file in my typescript code, it is referencing the wrong one: import styles from "somefile.scss" The typescript part works fine with the correct import (.scss ...