Integrating reference parameters in Angular 8

The TypeScript code currently looks like this:

callSomeMethod(data){
  let test2 : CommonModel[] = [{ name: 'testing'}];
  data = test2;
  console.log('data');console.log(data);
}
testRef(){
  let test : CommonModel[] = [];
  this.callSomeMethod(test);
  console.log('test');console.log(test);
}

I have a variable named 'test' that is of object/array type. I pass it as a parameter and call the method callSomeMethod(). I want to update this 'test' variable within the method.

However, after the method call finishes, the result is still empty.

How can I correctly retrieve the updated value?

Answer №1

When using the let declaration, a block-scoped local variable is declared. In this case, test is a block level variable. You need to reassign the results from callSomeMethod back to this variable in order to update it.

test = this.callSomeMethod(test);

Here is a Live Demo (Types have been removed for demonstration purposes) :

function callSomeMethod(data) {
  let test2 = [{ name: 'testing'}];
  data = test2;
  return data;
};

function testRef() {
  let test = [];
  test = this.callSomeMethod(test);
  console.log(test);
};

testRef();

Answer №2

To add the value to the original array, you must push it.

addDataToArray(data) {
  let newData: CommonModel[] = [{ name: 'new data' }];
  data.push(...newData);
}

updateArray() {
  let dataArray: CommonModel[] = [];
  this.addDataToArray(dataArray);
}

Alternatively, you can also return the value from the function.

returnData(): CommonModel[] {
  let newData: CommonModel[] = [{ name: 'new data' }];
  return newData;
}

updateArray() {
  let dataArray: CommonModel[] = [];
  dataArray = this.returnData();
}

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

Unable to persist AWS CDK ec2.Instance userData configuration

Trying to launch an ec2 instance with AWS CDK has been successful, but I am struggling to make the userData persistent so it runs on every boot. Despite searching extensively, I couldn't find any documentation on how to achieve this. The code below wo ...

Retrieve the implementation of an interface method directly from the constructor of the class that implements it

I am looking to create a function that takes a string and another function as arguments and returns a string: interface Foo { ConditionalColor(color: string, condition: (arg: any) => boolean): string; } I attempted to pass the ConditionalColor metho ...

Error in TypeScript: It is not possible to use a component with MUI styling as a JSX element

I can't figure out what's going wrong. I'm attempting to include a child component in the main page, and I have a feeling it has something to do with MUI styles being applied at the end. I removed all unnecessary code and still encounter thi ...

A step-by-step guide on sending a fetch request to TinyURL

I have been attempting to send a post request using fetch to tinyURL in order to shorten a URL that is generated on my website. The following code shows how I am currently writing the script, however, it seems like it's not returning the shortened URL ...

Discovering nested trees within a tree structure in typescript

Imagine having a tree structure in JavaScript like this: a1 --b ----c1 a2 --b2 --b3 ----c2 If you needed to find c2, the path would be a2->b3->c2 Now, consider the following JSON object representing a family tree: treeFamily = { name ...

Tips for styling the Button component in the shadcn/ui library for maximum impact

I'm currently working on a project using the shadcn/ui library. How can I properly customize it to meet my specific needs? For example, let's say I require an extra large red rounded Button for a call-to-action button in my project. What would be ...

Angular File Upload Button Tutorial

English is not my first language, so please excuse any mistakes. I recently started learning Angular and I'm attempting to build a file upload button that lets users upload files based on dropdown menu options (such as USA States). Once uploaded, the ...

Using Angular 4's ngComponentOutlet to showcase ContentChildren that are dynamically changing

My main objective is to create a unique container component with a dynamic list of customized card components that can be accessed individually (instead of as a group using ng-content). <custom-card-holder> <custom-card></custom-card> ...

Exploring Generic Features in Typescript Version 1.8.2

An error has been highlighted in the code snippet below: Cannot find name TEntity createEntity<TEntity>() : Promise<TEntity> { let type = typeof(TEntity); } What is the correct way to use the TEntity parameter wi ...

Angular 5 and the benefits of concurrent requests

My goal is to execute multiple requests in parallel, fetch the results, and combine them. To achieve this, I have implemented the following function: getStudent(query): Observable<any> { const code = this.http.get( `http://localhost ...

Having trouble with my React component timer not functioning properly

How can I utilize the Header Component as a Clock timer for my webpage to update every second? Despite searching on Google, I couldn't find examples that match my requirements. Why is the tick() function not functioning properly even though there are ...

Is it necessary to list all potential strings for accessibilityRole?

When working with accessibilityRole in React Native, I am wondering if there is a way to import all the possible strings instead of typing them out manually. createAccessibilityRole(parent: Element): string { if(isLink) return 'link' return ...

Assign a variable with the value returned by a function

Can you help me with this question I have about validating fields with a function using AbstractControl? errorVar: boolean = false function(c: AbstractControl): {[key: string]: string } | null { // validation if 'test' is true or not goes here ...

Obtain abbreviated names for the days of the week starting from Monday to Sunday using JavaScript

Is there a way to retrieve the abbreviated names of each day of the week in JavaScript, starting from Monday through Sunday? ...

Redux toolkit causing issues with triggering epics in Redux observable

I followed the documentation and implemented the following: middleware/index.ts import { combineEpics } from "redux-observable"; import userEpic from "./userEpic"; export const rootEpic = combineEpics( userEpic, ); store.ts import { configureStore } ...

What is the generic type that can be used for the arguments in

One function I've been working on is called time const time = <T>(fn: (...args: any[]) => Promise<T>, ...args: any[]): Promise<T> => { return new Promise(async (resolve, reject) => { const timer = setTimeout(() => r ...

What is the process for importing a TypeScript module exclusively through typings without having to download it separately?

Currently, I am working on a widget for a website that is already utilizing jQuery and I am using TypeScript. The goal is to embed my output into the host website while taking advantage of the existing jQuery library loaded by the host site. In order to r ...

What is the best way to remove query string parameters prior to running a function when a button is clicked?

I'm facing an issue trying to implement a button that filters events based on their tags. The problem arises when the tag value in the query string parameter does not clear when other buttons are clicked. Instead, the new filter tag value adds up with ...

How can I determine the data type of an Array element contained within an Interface member?

Is there a way to extract the type of key3 in MyInterface2 and use it in key3Value, similar to key2Value? interface MyInterface { key1: { key2: string } } const key2Value: MyInterface['key1']['key2'] = 'Hi' / ...

typescriptIs there a more efficient approach to typing optional values without a default value in

In my React application with TypeScript, I am using the following code to provide typed props: type ScheduleBoxContentProps = { desc: ReactNode, lottie: LottieProps, } & Partial<{className: string}>; I want the className prop to be optional ...