Angular中调用this.send()报TypeError未定义属性错误求助
问题:调用
this.send()时出现TypeError: Cannot read properties of undefined reading 'angular' 我使用如下函数实现文件上传:
async uploadFile(file) { let promise = new Promise((resolve, reject) => { bucket.upload(params, function (err, data) { this.file=`<a href='${this.FileName}' target=_blank'>File</a>`; this.send(); resolve(this.FileName);调用
this.send()时,在该行出现错误:ERROR TypeError: Cannot read properties of undefined reading angular
解决建议
- 用箭头函数修正
this指向:bucket.upload的普通回调函数会创建独立的作用域,导致this不再指向组件实例。换成箭头函数可以继承外层作用域的this,就能正常访问send()方法:async uploadFile(file) { let promise = new Promise((resolve, reject) => { // 把普通函数改成箭头函数 bucket.upload(params, (err, data) => { // 修复target属性的引号缺失问题 this.file=`<a href='${this.FileName}' target='_blank'>File</a>`; this.send(); resolve(this.FileName); }); }); return promise; } - 提前保存
this引用:如果不想用箭头函数,可以在回调外部先把当前组件的this存为变量,回调里用这个变量替代this:async uploadFile(file) { const that = this; // 保存当前组件的this let promise = new Promise((resolve, reject) => { bucket.upload(params, function (err, data) { that.file=`<a href='${that.FileName}' target='_blank'>File</a>`; that.send(); resolve(that.FileName); }); }); return promise; } - 补全代码语法:你提供的代码片段存在语法缺失(比如Promise、函数的闭合括号未写完),
target属性值也缺少引号,这些语法问题可能引发额外错误,建议先补全并修正。
内容的提问来源于stack exchange,提问作者user3653474
相关产品推荐
相关产品推荐

