Angular: Embed the user's ID into the payload

Is there a way to automatically retrieve the user id of the logged-in user and include it in the payload when they want to update their data without having to manually input their id?

  • MY LOGIN COMPONENT

    export class LoginComponent {
    
    studentForm: FormGroup;
    student: any;
    
     constructor(
      private fb: FormBuilder,
      private crudService: CrudService,
      private router: Router,
      private toastr: ToastrService) {
    
      this.studentForm = this.fb.group({
        id: ['', Validators.compose([Validators.required])],
        password: ['', Validators.compose([Validators.required])]
      });
    }
    
    saveStudentDetails(values) {
      const studentData = {};
    
      studentData['id'] =  values.id;
      studentData['password'] =  values.password;
    
      this.crudService.loginstudent(studentData).subscribe(result => {
        this.student = result;
        this.toastr.success('You are logged in', 'Success !', { positionClass: 'toast-bottom-right' });
        console.log(this.crudService.loginstudent);
        this.router.navigate(['/address']);
      },
        err => {
          console.log('status code ->' + err.status);
          this.toastr.error('Please try again', 'Error !', { positionClass: 'toast-bottom-right' });
     });
    }}
    

// MY EDIT COMPONENT

saveStudentDetails(values) {
  // const studentData = new FormData();
  const studentData = {};

  studentData['s_pNumber'] =  values.s_pNumber;
  studentData['s_address'] =  values.s_address;
  studentData['s_pCode'] =  values.s_pCode;
  studentData['s_city'] =  values.s_city;
  studentData['s_state'] =  values.s_state;
  studentData['s_country'] =  values.s_country;

  this.crudService.createAddress(studentData).subscribe(result => {
    // this.student = result;
    this.toastr.success('Your data has been inserted', 'Success !', { positionClass: 'toast-bottom-right' });
    // this.router.navigate(['/finance']);
  },
    err => {
      console.log('status code ->' + err.status);
      this.toastr.error('Please try again', 'Error !', { positionClass: 'toast-bottom-right' });
});

}

// THIS IS MY SERVICE

createAddress(data) {

const postHttpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json'
  })
};

postHttpOptions['observe'] = 'response';

return this.http.put(this.url + '/address/${id}', data);

}

I'm unsure if I'm approaching this correctly. Can someone advise me on how to include the user id in the payload sent to the backend? Thank you.

Answer №1

// Here is a code snippet demonstrating the proper usage of backticks in JavaScript

// Change this
return this.http.put(this.url + '/address/${id}', data);

//to this
return this.http.put(`${this.url}/address/${id}`, data);

//use the backtick
`

// not this
'

Here is an image demonstrating the use of backticks

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

Exploring the potential of Angular2's WebSocket service by efficiently accessing the parent component

I need some assistance with implementing WebSockets in my angular2 application. However, I've encountered a minor issue that I can't seem to solve. Here's what I have so far: I've created a service that has a method for creating a WebS ...

Identifying Data Types in Typescript Using a Union Type Guard

I came across this interesting type guard: enum X { A = "1" } const isNullableX = (value: any): value is X | null => false let bar: string | null = '' if (isNullableX(bar)) { console.log(bar) } Surprisingly, in the last con ...

The PrimeNg p-calendar is showing an incorrect month for the selected date

Utilizing the p-calendar component from primeNg has resulted in a discrepancy when comparing or checking dates, specifically returning an incorrect month. <p-calendar [locale]="nl" [inline]="true" [showOtherMonths]=" ...

Steps to create an instance method that only accepts the name of another instance method

I am looking to enhance an object by adding a method that specifically accepts the name of another method within the object. How can I achieve this in a way that dynamically narrows down the accepted names of methods, without hardcoding them? Let's t ...

one-time occurrence of $mdToast injection within a parent class

Seeking advice on how to efficiently place a single instance of $mdToast (from Angular Material) into a base class (Typescript). In my UI, I have five tabs with separate controller instances and it seemed logical to centralize the $mdToast declaration in a ...

What is the process for combining and compressing an Angular 2 application?

I am currently trying to concatenate and minify an angular2 application. My approach so far involved concatenating all my *.js files (boot.js, application.js then all components) into one file and injecting it into my index.html. I also removed the <s ...

Preventing recursive updates or endless loops while utilizing React's useMemo function

I'm currently working on updating a react table data with asynchronous data. In my initial attempt, the memo function doesn't seem to be called: export const DataTableComponent = (props: State) => { let internal_data: TableData[] = []; ...

Tips for distinguishing a mapped type using Pick from the original type when every property is optional

I am working with a custom type called ColumnSetting, which is a subset of another type called Column. The original Column type has most properties listed as optional: type ColumnSetting = Pick<Column, 'colId' | 'width' | 'sort ...

It seems that Angular2 Universal is experiencing some instability as it crashes frequently with the message "[nodemon] app crashed - waiting for file

After trying to work with the starter repo from my Angular class, I've found it to be quite unstable. It seems to be working locally when hitting the same service as remote, but I keep encountering errors. I have followed all the instructions: npm r ...

How can I iterate over a specific range in Angular (version 12 and higher) instead of looping through the entire array?

I need help with working with an array called bars stored in a foo property. In my HTML template, I am able to loop through the array like this: <div *ngFor="let bar of foo.bars"> <!-- do something with bar --> </div> Howeve ...

Fixing vulnerabilities in npm requires Angular 7, but implementing them in an Ionic 3 project may lead to further complications

I have a query related to my Ionic 3 project. Upon running npm audit, I found 10 vulnerabilities that need to be fixed. However, both fixes require Angular 7, and I am aware that Ionic 3 only supports Angular 5. My question is, is there a way to address t ...

Issue with NextJS Image Optimization in Vercel's production environment

As of now, I am developing a NextJS application that will eventually be deployed with multiple domains on Vercel. One of the key features of my application is the dynamic rendering of images. While all images display correctly in the preview environment on ...

Is it possible to add new values to a GraphQL query?

I am currently utilizing GraphQL and Typeorm in conjunction with an Oracle Database, specifically focusing on retrieving all data from a specific table. The query that is being executed is: SELECT "inventory"."id" AS "inventory_id", "inventory"."value" AS ...

Setting up an Ionic 5.24 / Capacitor 2.0.1 / Angular 9.1.2 project to view TypeScript sources while debugging in AVD using Chrome DevTools

I'm having trouble configuring an Ionic (5.24) project to access the TypeScript sources while debugging on an Android Virtual Device using Chrome DevTools. Capacitor version: 2.0.1 Angular version: 9.1.2 Here's what I have tried: ionic cap ru ...

The attribute 'xxx' is not found within the 'Readonly<{}>' type

I am currently in the process of writing tests for a React Typescript component. App.tsx: import * as React from 'react'; import { Button } from 'react-bootstrap'; interface Igift { id: number; } interface IAppState { gifts: Igi ...

Exploring the nativeElement property of a customized Angular HTML element

In my Angular Jasmine Unit Test, I am testing a third-party slider component in my application using the following code snippet: Here is the HTML: <ui-switch id="EditSwitch" name="EditSwitch" (change)="togglePageState()"></ui-switch> And her ...

What are the steps to utilize dismissableMask feature in PrimeNG?

Trying to hide a dialog by clicking outside of it seems tricky with PrimeNG's dismissableMask. Does anyone have a solution for this? HTML Code <button type="text" (click)="showDialog()" pButton icon="fa-external-link-square" label="Show"></ ...

Leverage the power of an Angular component for repeated

Attempting to recycle an Angular component within the given tree structure. https://i.sstatic.net/LVvwO.png The desired component, existing-savings, is located in transfer-guide. Trying to utilize this component in retirement-contributions-information. ...

Achieve validation of numerous variables without the need for a string of if-else

If we have three variables, such as firstName, lastName, and email, how can we check if they are empty or not without using multiple if else blocks? let firstName = "John"; let lastName = "Doe"; let email = "john.doe@example.com"; if (firstName.trim() == ...

How exactly does the 'this' type in TypeScript determine its own type inferences?

When working with TypeScript, I wanted to use the this keyword to type certain properties of my class. However, I encountered a problem that I couldn't figure out how to solve. What I was trying to achieve is something like this: export class Animal{ ...