0
我有private
变量constructor
和public
变量在class
。如何访问此函数内的这个变量
我使用this
关键字引用这个变量和函数。
我得到undefined
如果我尝试访问此函数内的这些变量。
我是typescript
的新手,如何在此函数内部访问此变量?
技术:打字稿,角2,角1.6.5,JavaScript的
管理,公司settings.ts
import { Component } from '../../../../common/extentions/to-angular2';
import { Http } from '@angular/http';
export class AdminCompanySettings {
public company: any;
constructor(private $http: ng.IHttpService) {
//
}
this.company = "New company";
console.log("Prints all public variables", this); //prints all variables
var data = { url: www.google.com, data: { user: value } }
this.$http(data).then(function (response) {
console.log(response);
console.log(this.company); // undefined cannot access company
console.log("Prints window object", this); //this will print window
//and not company var or
//other scope vars
}).catch(function (error) {
console.log(error);
});
}
我怀疑它可以通过.bind(this)
可以使用,但我不太熟悉在哪里添加.bind();
https://angular.io/guide/http供参考。
值,你可以使用箭头函数表达式,它保留了这个值。利用'()=> {}'函数来代替函数。 –
你的代码是否在任何'method'之外并且你的'class'没有正确关闭是否正常? –
[如何在回调中访问正确的\'this \'](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) ) – Alex