As I was working on creating an extension method using typeScript, the main goal was to establish a static or normal variable within the method. The ServiceCollector method was invoked three times in order to send and store data or objects in an array.
Below is the code snippet:
import { Employee } from "./Employee.model";
let datafetcher: Employee[] = [];
declare global {
interface Object {
ServiceCollector(data): any[];
}
}
Object.defineProperty(Object.prototype, 'ServiceCollector', {
value: function(data) {
datafetcher.push(data);
console.log(datafetcher);
return "done";
},
enumerable: false
});
The array datafetcher
successfully stores the values. However, it encounters an issue where it overrides all previous data with the most recent one.
Array : 0: {code: 101, FirstName: "Aditya"}
/*Adding another value */
Array : 0: {code: 102, FirstName: "Aryan"}
Array : 1: {code: 102, FirstName: "Aryan"}
/*Adding another value */
Array : 0: {code: 103, FirstName: "Kundan"}
Array : 1: {code: 103, FirstName: "Kundan"}
Array : 2: {code: 103, FirstName: "Kundan"}
I've put effort into finding a solution but haven't been able to pinpoint why this behavior persists. This is how the ServiceCollector method is being called
import { Component, OnInit } from '@angular/core';
import { Employee } from './Employee.model';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
EmployeeObject: Employee = {};
ParentObject: Object = {};
submit1() {
this.EmployeeObject.code = 102;
this.EmployeeObject.FirstName = 'Aryan Toke';
console.log("Submit 1", this.EmployeeObject);
this.ParentObject.ServiceCollector(this.EmployeeObject);
}
submit2() {
this.EmployeeObject.code = 103;
this.EmployeeObject.FirstName = 'Kundan Toke';
console.log("Submit 2", this.EmployeeObject);
this.ParentObject.ServiceCollector(this.EmployeeObject);
}
ngOnInit(): void {
this.EmployeeObject.code = 101;
this.EmployeeObject.FirstName = 'Aditya Toke';
console.log("ngoninit", this.EmployeeObject);
this.ParentObject.ServiceCollector(this.EmployeeObject);
}
}
Upon clicking the submit1()
and submit2()
buttons, the respective methods are triggered.