The repository injected into NestJs using TypeORM suddenly becomes null

In my code, I am fetching Requisition data from an external system using the following approach:

init() {
  const requisitionData = this.loginMb().pipe(
    map(response => response.data.token),
    switchMap(loginData => this.getRequisitions(loginData)),
    map(response => response.data),
  );
  requisitionData.subscribe(this.processData);
}

This is the processData() function:

processData(response: any) {
  const requisitions = response.content.data;
  for (const p of requisitions) {
    const req = new Requisition(); // Requisition is the TypeORM entity
    req.title = p.title;
    req.reference = p.reference;
    // other fields 

    this.repo.save(requisition);
  }

Below is the constructor:

@Injectable()
export class RequisitionSync {
  constructor(
    @InjectRepository(Requisition) private readonly repo: Repository<Requisition>,
    private readonly httpService: HttpService,
  ) {}

The issue I am encountering is that within the processData() function, this.repo is becoming undefined. Interestingly, if I output console.log(this.repo) within the init() function, it is not undefined.

Answer №1

Due to the difference in lexical binding of this between the class and the subscribe method, it will be necessary to explore alternative methods for managing the function. I recommend considering the use of an additional map or a mergeMap to execute your this.processData within it, followed by subscription to allow events to unfold naturally. This approach essentially creates a callchain as follows:

init() {
  const requisitionData = this.loginMb().pipe(
    map(response => response.data.token),
    switchMap(loginData => this.getRequisitions(loginData)),
    map(response => response.data),
    map(this.processData), // or mergeMap(data => this.processData(data)), your choice
  );
  requisitionData.subscribe();
}

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 multiple states within an interval function in React Native

I'm struggling to find the right words for this question. I've encountered an issue where I need to constantly check and update a complex state object within an interval loop in my program. To simplify, let's say it consists of just a counte ...

Issue TS2307 encountered following the transition from Angular 11 to Angular 12 in a project migration

After upgrading my project from Angular 11 to Angular 12, I encountered errors while using the ng update command. Instead of troubleshooting further, I decided to take a more manual approach. I started by creating a brand new Angular 12 project, re-adding ...

Using an Angular interface for an HTTP request: The statusText message reads as "Error: Unable to Determine."

I've been working on calling an API as an example in Angular using an interface. The API I'm trying to access is located at https://jsonplaceholder.typicode.com/posts. Unfortunately, I encountered the following error message: ERROR HttpErrorResp ...

Generating a dynamic SQL Insert statement based on an array object

I am currently working on a Typescript project where I am looking to optimize my Insert function by creating one Insert statement for all the elements in an object, rather than generating multiple Inserts for each array item. Here is the code snippet of m ...

When a new form object is assigned, the outputFromObservable breaks due to Angular typed form events

Apologies for the lengthy title. In one of my components, I have an Angular v18 typed form that exposes the ValueChangeEvent as an output event using the outputFromObservable() function: export class SessionEditFormComponent { private fs = inject(Sessio ...

Error encountered during conversion to Typescript for select event and default value

When trying to set the defaultValue in a Select component, TSlint throws an error - Type 'string' is not assignable to type 'ChangeEvent<HTMLInputElement> | undefined - for the code snippet below: const App = () => { const [ mont ...

Looking to receive detailed compiler error messages along with full imports in Visual Studio Code for TypeScript?

Currently, I am trying to edit a piece of typescript code in Visual Studio Code. However, I encountered a compiler error message that looks like this: The error states: Type 'import(\"c:/path/to/project/node_modules/@com.m...' is not assign ...

Issues arising when routing ffmpeg to flac encoder

I am facing an issue with encoding a flac file with seektables. The ffmpeg's flac encoder does not include seektables, so I have to resort to using the flac Command Line Interface (CLI). My goal is to convert any arbitrary audio file into a seekable f ...

The argument '$0' provided for the pipe 'CurrencyPipe' is not valid

When retrieving data from the backend, I receive $0, but I need to display it as $0.00 in my user interface. <span [innerHTML]="session.balance | currency :'USD': true:'1.2-2'"></span> I'm encountering an issue where ...

Filling a data entry with simultaneous commitments

Sample code: type Alphabet = 'a' | 'b' | 'c'; const alphabetMap: Record<Alphabet, null> = { 'a': null, 'b': null, 'c': null} // Select any asynchronous processing function you prefer funct ...

The value of this.$refs.<refField> in Vue.js with TypeScript is not defined

During the process of converting my VueJs project to TypeScript, I encountered an error related to TypeScript. This issue arises from a component with a custom v-model implementation. In the HTML, there is an input field with a 'plate' ref that ...

Using React to update the state of an array of objects

I'm faced with a challenge in changing the properties of an object within an array of objects at a specific index using a function: const handleEdit= (index) =>{ if(itemList[index].edit==true){ const copied=[...itemList]; const item2 = {...ite ...

What steps can I take to make sure that the asynchronous initialization in the Angular service constructor has finished before proceeding?

Hello experts, can you advise on ensuring that asynchronous initialization in the service constructor is completed before calling other functions within the class? constructor() { var sock = new SockJS(this._chatUrl); this.stompClient = Stomp.ov ...

Trigger refetchQueries post-execution of a mutation operation

In the past, I executed a mutation in a similar manner as shown below: export const useEditLocationName = () => { const [editFavoriteLocationName] = useEditFavoriteLocationNameMutation({ refetchQueries: [{ query: GetMyFavouritePlacesDocument}], ...

Having difficulty retrieving an angular file from a location outside of the asset folder

I'm encountering issues with a small project that is meant to read a log and present it in table format. Here is the outline of the project structure: project structure Within the LOG directory, I should be able to access motore.log from my DataServi ...

Testing an asynchronous function in JavaScript can lead to the error message: "Have you neglected to utilize await?"

Here is an example of the code I am working with: public getUrl(url) { //returns URL ... } public getResponseFromURL(): container { let myStatus = 4; const abc = http.get(url, (respon) => const { statusCode } = respon; myStatus = statusCode ...

The method of evaluating in-line is distinct from evaluating outside of the

What causes the compiler to produce different results for these two mapped types? type NonNullableObj1<O> = {[Key in keyof O] : O[Key] extends null ? never : O[Key]} type NotNull<T> = T extends null ? never : T; type NonNullableObj2<T> = ...

Tips for resolving the issue when Chrome is able to load the page but Postman cannot find it

I'm encountering a perplexing situation that is entirely new to me and difficult to comprehend. I find myself unable to decipher what exactly I am witnessing, leading to uncertainty about why it is occurring, not to mention the challenge of determinin ...

Adding images in real-time

I am currently working on an Angular application where I need to assign unique images to each button. Here is the HTML code snippet: <div *ngFor="let item of myItems"> <button class="custom-button"><img src="../../assets/img/flower.png ...

Mapping nested JSON to model in Angular2 - handling multiple API requests

Having trouble integrating two HTTP API Responses into my Model in Angular 2. The first API Call returns data like so: [{ "id": 410, "name": "Test customdata test", "layer": [79,94] }, { "id": 411, "name": "Test customdata test2", ...