this 变量是 Window 对象,或者在 then 方法的 promise 中未定义
The this-variable is the Window object or undefined in the then-method of a promise
在ES2015(以前的ES6)中,我认为使用箭头语法应该导致this
变量成为您所在的对象,从而使旧的var that = this
技术过时。
但是,在我的函数中,对于 Promise 的then
部分,this
变量是Window
对象(在 Chrome 中)或undefined
(在 FF 和 IE11 中):
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
@inject(HttpClient)
export class InvoiceGenerator {
items = [];
constructor(http) {
this.http = http;
}
activate() {
this.http
.get(`http://${window.location.host}/api/invoice`)
.then(response => {
this.something = response.someProperty; // this is the Window
}).catch(err => {
console.log(err);
});
}
}
顺便说一下,我正在使用Aurelia,以防万一很重要。
如何在不使用旧var that = this
技术的情况下让this
变量成为我当前所在的对象(我的 Aurelia 视图模型)?
在回调中用"this"引用它之前,你需要在类中声明"something"属性,因为回调中的"this"不包含"something"属性,也不会创建它。
export class InvoiceGenerator {
something = [];
constructor(http) {
this.http = http;
}
activate() {
this.http
.get(`http://${window.location.host}/api/invoice`)
.then(response => {
this.something = response.someProperty; // this is the Window
}).catch(err => {
console.log(err);
});
}
}
我没有尝试过,但我相信打字稿会发现错误。
您是正确的,"箭头语法应引导this
变量成为您所在的对象",但您对"在哪个对象"中"感到困惑。执行此操作时:
this.http
.get(`http://${window.location.host}/api/invoice`)
.then(response => {
this.something = response.someProperty; // this is the Window object
});
它相当于这个:
let thenFn = response => { this.something = response.someProperty; }
this.http
.get(`http://${window.location.host}/api/invoice`)
.then(thenFn);
在括号(then(response => ...)
)内定义函数不会改变您在this.http
存在的同一上下文中定义它的事实 - 在您的情况下显然是window
。
不幸的是,我无法告诉您如何this
引用您的Aurelia视图模型,因为您尚未显示视图模型代码或任何其他上下文。
相关文章:
- $resource上带有.then()函数的角度自定义方法导致错误
- 将数据从promise then方法传递到对象方法
- Angular Provider/JS-如何访问'叔叔方法'从$http().then()
- 为什么 then() 链式方法不按顺序运行
- “未捕获(在承诺中)”在获取“then”方法中调用拒绝函数时
- 如何重写这段代码,使执行不必从Javascript Promise.then()方法开始
- 未捕获的类型错误:无法调用未定义的方法“then”
- 获取类型错误:无法在 angularjs 控制器中调用未定义的方法 'then'
- .done 或 .then 中的茉莉花测试方法
- TypeError:无法调用未定义的 Angularjs 的方法 'then'
- 为什么来自 Promise '.then' 方法的回调是反模式
- 问.js节点承诺.“套接字”上缺少错误处理程序.类型错误:无法调用未定义的方法“then”
- 与茉莉花中 ES6 承诺的 then/catch 方法同步
- 用javascript实现if-then-else-if-else堆栈的更简单方法是什么
- 角美元http.Post then方法不起作用
- 用".then"链接bluebird中的异步函数.什么是最好的方法
- 使用AngularJS创建一个动态表——从success/error方法到.then()方法需要帮助
- 添加“then"方法在预定义的“finally”之前放入$promise链中.方法
- Sinon测试ember.js .then方法
- 点击重载按钮后,AngularJS-then()方法未被调用