Troubleshooting a database update issue within an Angular and NestJS application

Hey there, I am a newcomer to both Angular and NestJS. I'm currently facing an issue with updating a specific row in my database through the frontend. While I can easily insert new data, updating seems to be problematic. Here's how my files are structured:

Front-End

update.component.html

<div>
    <form class="form">
      <div class="pageTitle title"> Update Structure/Department Information </div>
      <div class="secondaryTitle title">Insert Department Name you want to update</div>
      <input  type="text" class="name formEntry" placeholder="Department Name" name="something" [(ngModel)] = "MyDept"/>
      <button class="get formEntry" (click)="getManager()">Get</button>
      <ul class="flight_headers" *ngFor="let org of barg">
        <li class="departs cell"> Description: <input type="text" name="DN" [(ngModel)]="org.description"/> </li><br/>
        <li class="arrives cell"> managing department:  <input type="text" name="bDN" [(ngModel)]="org.managing_department"/> </li> <br/>
        <button class="get formEntry" (click)="update(org)">Update</button>
      </ul>

update.component.ts

import { Component, OnInit } from '@angular/core';
import { OrganiService } from '../organi.service';
import { Organi } from '../organi.model';

@Component({
  selector: 'app-update',
  templateUrl: './update.component.html',
  styleUrls: ['./update.component.scss']
})
export class UpdateComponent implements OnInit {

  constructor(private organiService: OrganiService) { }


  barg: Organi[];

  ngOnInit(): void {
  }

  getManager(): void{
      let name:string = this.MyDept;
      this.organiService.getManagingStructures(name).subscribe(data=>{
        this.barg = data;
      })
      }

  update(org: Organi): void{
    this.organiService.updateStructure(org);
    
    window.location.reload()
  }
}

organi.service.ts

import { Injectable, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient} from '@angular/common/http';
import { Organi } from './organi.model';

@Injectable({
  providedIn: 'root'
})
export class OrganiService {

  constructor(private http: HttpClient) {
  }
  getManagingStructures(name: string): Observable<any> {
    return this.http.get('http://localhost:3000/structures/query/'+name);
  }
  getSubordinateStructures(name: string): Observable<any> {
    return this.http.get('http://localhost:3000/structures/query2/'+name);
  }

  postStructure(org: Organi) {
    return this.http.post('http://localhost:3000/structures',org).subscribe(data =>{
      console.log("New Structure Created!")
    })
  }

  updateStructure(myData: Organi) {
    return this.http.post('http://localhost:3000/structures/update',myData);
  }

  deleteStructure(id: number) {
    
  }
}

Back-end

structures.controller.ts

import { Controller, Get, Post, Param, Body, Put, Delete, Patch } from '@nestjs/common';
import { StructuresService } from './structures.service';
import { Structure } from './structure.model';
import { Organization } from './structure.entity';

@Controller('structures')
export class StructuresController {
  constructor(private readonly structuresService: StructuresService) {}


  @Get()
  findAll() {
    return this.structuresService.findAll();
  }

  @Get("query/:name")
  async query(@Param('name') name): Promise<any> {
    return this.structuresService.query(name);
  }
  @Get("query2/:boss")
  async query2(@Param('boss') boss): Promise<any> {
    return this.structuresService.query2(boss);
  }
  
  @Post()
  async create(@Body() structure: Structure): Promise<Organization[]> {
    return this.structuresService.create(structure);
  }

  @Patch("update")
  async update(@Body() structure: Structure): Promise<any> {
    return this.structuresService.update(structure);
  }

 /* @Delete(':id')
  remove(@Param('id') id: string) {
    return this.structuresService.remove(+id);
  } */
}

structures.services.ts

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, UpdateResult } from 'typeorm';
import { Organization } from './structure.entity';
import { Structure } from './structure.model';
//import { structure } from './structure.model'
@Injectable()
export class StructuresService {

    constructor(
    @InjectRepository(Organization)
    private readonly structureRepository: Repository<Organization>,
    ){}

  async findAll(): Promise<any> {
    return this.structureRepository.find();
  }
  
  async findManager(CEO: string): Promise<any> {
    return this.structureRepository.find();
  }

  async query(Myname: string): Promise<any> {
   return await this.structureRepository.find({name: Myname});
  }
  async query2(boss: string): Promise<any> {
   return await this.structureRepository.find({managing_department: boss});
  }

  async create(structure: Structure): Promise<any> {
    return await this.structureRepository.save(structure);
  }

  async update(structure: Structure): Promise<UpdateResult> {
    return await this.structureRepository.update(structure.id, structure);
  }

}

Answer №1

It appears that you may have forgotten to call the update method within the updateStructure() function in OrganiSevice. The http.post() function is not being triggered because there is no subscribe() or toPromise() method included.

Answer №2

It turns out that the CORS functionality was preventing the request from being processed due to my usage of the @Patch decorator. Once I switched it to the @Put decorator, everything ran smoothly.

Answer №3

It seems like you missed adding the MyDept property in the UpdateComponent class

UPDATE

Also, don't forget to subscribe to the updateStructure(org) method

If you fail to subscribe to the observable method, it will not be called

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

Having trouble with an Angular HTTP PUT request returning a 404 error for a valid URL on a JSON server!

After trying to implement Angular HTTP put using reactive forms for the first time, I encountered an issue. Whenever I use the code provided, I receive a 404 error. The error specifically points to a server URL that cannot be found (XHR PUT http://localhos ...

compileOnSave has ceased to function

After successfully building my ng4 project with "@angular/material": "^2.0.0-beta.6" and having the compileOnSave feature work fine, I decided to add the following dependencies: "@ngx-translate/core": "^8.0.0", "@ngx-translate/http-loader": "^2.0.0", "an ...

Angular7 instances encounter the issue of undefined when referencing "this"

After incorporating a custom confirm dialog into a function, I noticed that the reference to "this" became undefined in all parts of the code except for within the dialog function. The function looks like this: onDelete(CTId) { this.confirmDialogServ ...

Display event using Angular

I am currently working on an Angular project where I need to print a specific area of the page. While I know that this can be done using media CSS, it is causing issues for me due to the numerous print functionalities present in the project. I am attemptin ...

The namespace 'angular' seems to be missing

I recently upgraded my hybrid Angular app from AngularJS 1.5.8 to Angular 5.2.9 following the steps outlined in the official upgrade guide. Everything was working perfectly until I decided to take it a step further and update to Angular 6.0.1, which result ...

What steps are involved in creating a local unleash client for feature flagging?

Currently attempting to implement a feature flag for a Typescript project using code from the Unleash Client. Here is where I am creating and connecting to an instance of unleash with a local unleash setup as outlined in this documentation: Unleash GitHub ...

There is an issue with types in React when using TypeScript: The type '(user: User) => Element' cannot be assigned to the type '((props: User) => any) & ReactNode'

I'm encountering an error in the terminal and need some assistance. I am not well-versed in TypeScript, so any guidance to resolve this issue would be highly appreciated. https://i.stack.imgur.com/PWATV.png The Loadable component code: import { Circ ...

What is the best way to avoid passing a value to a component in nextjs?

I'm trying to make this component static and reusable across different pages without passing a parameter when calling it. Is there a way to achieve this while following the official documentation? component: import { GetStaticProps, InferGetServerSid ...

reasons why my custom attribute directive isn't functioning properly with data binding

Here is a snippet of the code I am working on, with some parts omitted for brevity: template.html ... <tr *ngFor="let item of getProducts(); let i = index" [pa-attr]="getProducts().length < 6 ? 'bg-success' : 'bg-warning'" ...

Display a Carousel in Angular4 based on the selected value from a dropdown

My goal is to create a dynamic carousel that displays a football club's players when the user selects the team from a dropdown menu. The team options are loaded from a database, as well as the player information. Currently, I am able to retrieve the ...

How can I use Angular2 to draw a square [input] number of times?

I need to create a specific number of squares within a container using Angular2. Can you please provide me with a straightforward example, preferably utilizing canvas? Currently, I have converted webpack starter for use with Angular: This is the code ins ...

Tips for using conditional rendering with React and TypeScript

Issue with Conditional Rendering in TypeScript It seems like I might have encountered a problem with the way I declare my components. Take a look at this TypeScript snippet: import React, { FunctionComponent } from 'react'; export const Chapte ...

Guide on integrating angular-schema-form into an Ionic 2.0 project using typescript

Recently, I embarked on creating an app with Ionic from scratch and decided to integrate the framework. While I faced no issues executing the example on a webpage, I encountered difficulties when attempting to do so with Ionic. To kickstart the project, ...

Compiling TypeScript: Using the `as` operator to convert and then destructure an array results in a compilation error, requiring an

I am currently utilizing TypeScript version 2.9.2. There is a static method in a third-party library called URI.js, which is declared as follows: joinPaths(...paths: (string | URI)[]): URI; I have a variable named urlPaths that is defined as urlPaths: s ...

Issue: Unable to link to 'options' as it is not recognized as a valid attribute of 'chart'

Here is a sample component code snippet: import { Component, OnInit, Input } from '@angular/core'; import { Observable } from 'rxjs/Rx'; @Component({ selector: 'chart', templateUrl: 'app/comps/chart.html', ...

Issues have arisen with the functionality of Ionic2-Calendar on the device

I'm currently working on a project that involves developing an Ionic 4 app with Angular 8. I've encountered a peculiar issue while using this calendar plugin. It seems similar to the problem discussed in this thread. Despite reaching out for sol ...

In TypeScript, is there a similar concept to "sealed" or "final" modifiers?

I'm currently working on incorporating a method in a superclass that should be accessible for use, but not modifiable, in subclasses. Take a look at the following: export abstract class BaseClass { universalBehavior(): void { doStuff(); / ...

The Ng-bootstrap dropdown menu fails to activate when clicked within a table row with a click event listener

By simply clicking on a table row, users can easily view the details. When I incorporate a 'ng-bootstrap' dropdown menu in the last column of the data table, it seems that clicking on the dropdown button does not open the menu as expected. Inste ...

Exploring Type Definitions in Vue Apollo version 4 and the Composition API

How can TypeScript be informed that Variables is the interface for the arguments of the myMutation function? interface Variables { uuid: string; value: string; } const { mutate: myMutation } = useMutation(myGqlMutation); I am look ...

Displaying random characters in place of Angular 6 font awesome icons

Recently, I started a new project with the angular cli and incorporated font-awesome 4.7.0. After that, I included it as a dependency in my angular.json file. "styles": [ "./node_modules/font-awesome/css/font-awesome.min.css", "./node ...