Currently, the ts code 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 'test' variable as object/array type. I use it as parameter and call callSomeMethod(). I want to change this 'test' variable in this method.
But when finish calling, the result is still empty now.
How can I get the value correct?
CodePudding user response:
The let declaration declares a block-scoped local variable. Hence, as test
is a block level variable. You have to assign back the results coming from callSomeMethod
to this variable to get it updated.
test = this.callSomeMethod(test);
Live Demo (Just for a demo purpose, I removed the types from the below code snippet) :
function callSomeMethod(data) {
let test2 = [{ name: 'testing'}];
data = test2;
return data;
};
function testRef() {
let test = [];
test = this.callSomeMethod(test);
console.log(test);
};
testRef();
CodePudding user response:
you have to push the value to the original array,
callSomeMethod(data) {
let test2: CommonModel[] = [{ name: 'testing' }];
data.push(...test2);
}
testRef() {
let test: CommonModel[] = [];
this.callSomeMethod(test);
}
or you can return the value from callSomeMethod
callSomeMethod(): CommonModel[] {
let test2: CommonModel[] = [{ name: 'testing' }];
return test2;
}
testRef() {
let test: CommonModel[] = [];
test = this.callSomeMethod();
}