Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript angular 2无法引用函数中的变量_Javascript_Angular - Fatal编程技术网

Javascript angular 2无法引用函数中的变量

Javascript angular 2无法引用函数中的变量,javascript,angular,Javascript,Angular,我有一个使用firebase函数的事件侦听器。在这种情况下,文件正在上传,并在完成后,我希望它运行在另一个文件中找到的功能。另一个文件中的代码的工作方式与它在onInit()中的工作方式相同 代码: fileButton.addEventListener('change',(e:any)=>{ //获取要上载的文件的路径 var filePath=(document.getElementById('filePathInp')).value; //获取文件: var file=e.target.

我有一个使用firebase函数的事件侦听器。在这种情况下,文件正在上传,并在完成后,我希望它运行在另一个文件中找到的功能。另一个文件中的代码的工作方式与它在onInit()中的工作方式相同

代码:

fileButton.addEventListener('change',(e:any)=>{
//获取要上载的文件的路径
var filePath=(document.getElementById('filePathInp')).value;
//获取文件:
var file=e.target.files[0];
//获取用户的ID
var user=JSON.parse(localStorage.getItem('user'));
//创建存储引用
如果(文件路径!=''){
var ref=(user.id)+'/'+filePath++'/'+file.name;
}否则{
var ref=(user.id)+'/'+file.name;
}
var storageRef=firebase.storage().ref(ref);
//上传文件
var task=storageRef.put(文件);
//更新进度条
task.on('state_changed',
功能进度(快照){
//计算百分比
变量百分比=(task.snapshot.bytesttransfered/task.snapshot.totalBytes)*100;
//显示完成的百分比
uploader.value=字符串(百分比);
},
功能(err){
//发生错误时抛出错误
抛出(错误);
},
函数完成(){
//完成后控制台日志
console.log('COMPLETE!!');
((FileuploadComponent)=>this.auth.sendFileStruct({msg:'hello'}).subscribe(data=>{}));
});
});

};
在用关键字
function
声明的函数中引用函数,而不再引用类。您可以这样使用箭头函数:

task.on('state_changed',
   snapshot => {/*progress function content*/},
   err => {/*error function content*/},
   ...
);
或者在变量中稍微优雅地绑定
,以保留引用

var that = this;
...
that.auth.sendFileStruct(...)

您已经定义了一个应该立即调用的函数,因此您必须这样做:

// add the parenthesis at the end 
 ((FileuploadComponent) => this.auth.sendFileStruct({msg: 'hello'}).subscribe(data => {}))(); 
或者将函数放入变量中,并通过当前this对象调用它