我有2个函数将在页面加载时执行,我在load1()函数中获取一个值,需要将其打印到其他函数load2()中。我得到了一个,但是编译错误“预期0个参数得到1个”,有人可以帮我吗。
<div>How to get the value from one function to other function in angular 6</div>
declare var require: any;
import { Component,OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
data:any;
idVal:number;
ngOnInit(){
this.load1();
}
load1(){
let data = [{"id":1},{"id":2},{"id":3}];
this.idVal = data[0].id;
this.load2(this.idVal);
}
load2(){
alert('load2');
console.log(this.idVal);
}
}
答案 0 :(得分:2)
load1(){
let data = [{"id":1},{"id":2},{"id":3}];
this.idVal = data[0].id;
this.load2(this.idVal);
}
load2(idVal: number){
alert('load2');
console.log(idVal);
}
答案 1 :(得分:0)
正如您在该代码段上所写,load2()
没有任何必需的参数。
因此,当您尝试在其上传递参数时,它将返回该错误。
您可以通过删除load1()
最后一行的参数来解决该问题。
load1(){
let data = [{"id":1},{"id":2},{"id":3}];
this.idVal = data[0].id;
this.load2();
}
load2(){
alert('load2');
console.log(this.idVal);
}
答案 2 :(得分:0)
load1(){
data = [{"id":1, name: "Ben Racicot"},{"id":2, name: "Some Guy"},{"id":3, name: "Some Girl"}];
firstID = data[0].id; // the first object's `id` value: `1`
firstName = data[0].name; // the first object's name value: `Ben Racicot`
this.load2(firstID, firstName);
}
load2(id, name){
console.log(id);
console.log(name);
}