如何在此函数中访问此变量

时间:2017-07-25 06:27:55

标签: javascript angular typescript this

我在private中的constructorpublic个变量中有class个变量。

我使用this关键字来引用这些变量和函数。

如果我尝试在此函数中访问此变量,我将获得undefined

我是typescript的新手,如何在此函数中访问此变量?

技术:Typescript,Angular 2,Angular 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

1 个答案:

答案 0 :(得分:7)

使用保留this

值的箭头功能
this.$http(data).then((response) => {
        console.log(response);
        console.log(this.company);
        console.log("Prints window object", this);
    }).catch(function (error) {
        console.log(error);
    });
相关问题