Event typeORM on afterUpdate in NestJS

After every update of my data in the log table, I want to insert an entry into another table. To achieve this, I have created an EntitySubscriberInterface. The event is triggering correctly, but the entity array does not include the updated id.

 async afterUpdate(event: UpdateEvent<any>) {
    console.log(event.entity);
    const book = event.entity;
    const authorId = book.authorId;
    console.log(newAuthorId);       
// this.myService.insertHistory(authorId , event.entity);

}

If anyone has any ideas or suggestions, they would be greatly appreciated. Thanks.

Answer №1

To retrieve data from a database, you have two options: either execute a findOne query as suggested by @Bramovic44, or implement an afterLoad method that is triggered after an entity has been loaded.

Below is a simple example to demonstrate this concept:

export class EntitySubscriber implements EntitySubscriberInterface<SomeEntity> {
  someEntity: SomeEntity;

  listenTo() {
    return SomeEntity;
  }

  afterLoad(someEntity: SomeEntity) {
    this.someEntity = someEntity;
  }

  async afterUpdate(event: UpdateEvent<SomeEntity>): Promise<any> {
    event.entity; // returns updated properties in entity
    this.someEntity; // returns entity prior to update with all properties
  }

Answer №2

The afterInsert method provides access to information, while with the afterUpdate method, you need to query the database for the entity.

const item = await connection
      .getRepository(item)
      .findOne(event.entity.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 method to access the information within the observer?

When I receive the data from the observer in the console, here is what I see: https://i.stack.imgur.com/dVzwu.png However, I am only interested in extracting this specific data from each item on the list: https://i.stack.imgur.com/g8oHL.png To extract ...

I am encountering 404 errors when attempting to load Angular2 files using Express - what could be causing this issue?

Having experience with using Express, I am attempting to apply the guidelines provided here to the express template. After generating the latest Express project, I included the following in my package.json file. "dependencies": { "angular ...

Changing the color of an input field in Angular Material to red

Below is an example of Angular code where the mat-form will turn red automatically if no value is entered. <mat-form-field> <input matInput placeholder="Enter your email" [formControl]="email" required> </mat-form-field> In the scenar ...

What is the primary purpose of the index.d.ts file in Typescript?

There are some projects that include all types declarations within the index.d.ts file. This eliminates the need for programmers to explicitly import types from other files. import { TheType } from './somefile.ts' Is this the proper way to use ...

Utilizing TypeScript's dynamic class method parameters

I've been working on integrating EventBus with TypeScript and I'm trying to create a dynamic parameter event in the emit method. How can I achieve this? interface IEventBusListener { (...params: any[]): void } class EventBus { constructo ...

selectize.js typescript: Unable to access values of an undefined object (reading '0')

I've been working on incorporating selectize.js into my project using webpack and typescript. After installing selectize.js and the necessary types, I added the following to my code: yarn add @selectize/selectize yarn add @types/select2 Within my c ...

Guide to inserting a marker on a leaflet map within an Angular component

In my Angular application, I am using Leaflet to display markers with coordinates retrieved from the backend. However, I noticed that the markers do not maintain their position when zooming in or out. They appear to be in a different location compared to ...

Storing data in Angular 2 services for safekeeping

I have multiple sub-components that each receive specific data from a main component. These sub-components only receive the data necessary for display purposes. My goal now is to create a service that can make a request to a server. The problem is, this re ...

Typescript objects may contain keys that are dependent on certain parameters

I have a challenge with constructing an object that requires querying multiple database tables, resulting in a time-consuming process. To address this issue, clients of the object need to specify which specific parts they require. For example, let's c ...

Switching the scope or zone in Angular when handling events external to Angular

Currently, I am utilizing an external library within my Angular 6 application that incorporates customizable event listeners. Specifically, I am employing flowchart.js, although similar issues may arise with other libraries. In the case of flowchart.js, i ...

Struggling with transferring data rows between tables in Angular with Angular Material

I have implemented a data table using angular material with initial data rows. Additionally, I have included an empty data table where rows can be transferred from the first table. Transferring rows from the first table to the second table is functioning ...

What is the process for specifying a data type for a pre-existing npm package module?

I am currently working on converting a codebase that utilizes nodemailer along with the nodemailer-html-to-text plugin to TypeScript. While nodemailer has @types definitions available, the same is not true for nodemailer-html-to-text. How can I go about ...

Transforming an Angular 1.x directive into Angular 2

I have been working on converting a wrap-bootstrap template with various widgets to Angular 2. The task of converting one particular widget has left me puzzled: .directive('changeLayout', function(){ return { restrict: 'A' ...

Managing business logic in an observable callback in Angular with TypeScript - what's the best approach?

Attempting to fetch data and perform a task upon success using an Angular HttpClient call has led me to the following scenario: return this.http.post('api/my-route', model).subscribe( data => ( this.data = data; ...

Converting a TypeScript array into a generic array of a specific class

I am attempting to convert a JSON source array with all string values into another array of typed objects, but I keep encountering errors. How can I correct this code properly? Thank you. Error 1: There is an issue with converting type '({ Id: string ...

Discover how to access all of the response headers from an HTTP request in Angular

Currently, I am utilizing HttpClient to make a request for a `json` file. My intention is to have the file cached using `ETag`, however, this feature does not seem to be functioning as expected. Upon investigation, it appears that the absence of sending of ...

Update the Ngrx reducer when the component is present on the page

One dilemma I am facing involves managing two components within a page - an update user form and a history of events. Each component has its own reducer (user and events). My goal is to update the list of events in the store through an API call once the us ...

What steps can be taken to resolve the issue with Angular routing?

import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import {HomeComponent} from "./home/home.component"; import {SettingsComponent} from "./settings/settings.component"; ...

What is the prescribed interface or datatype for symbol type in TypeScript with JavaScript?

I have a set of symbol values in JavaScript that I want to convert to TypeScript. // Defining object values in JavaScript const size = { Large: Symbol('large'), Medium: Symbol('medium') } What is the most efficient method to conv ...

An issue has been encountered: No NgModule metadata was discovered for 'AppModule' in the ngx-rocket Metronic theme

Task List [ ] Initialize [x] Build [x] Serve [ ] Test [ ] End-to-End test [ ] Generate [ ] Add [ ] Update [ ] Lint [ ] Internationalization [ ] Run [ ] Configure [ ] Help [ ] Version [ ] Documentation Is this a regression? This issue started occurring ...