How to access this variable inside this function

£可爱£侵袭症+ 提交于 2019-12-02 19:16:43

问题


I have private variables in constructor and public variables in the class.

I refer to this variables and functions using this keyword.

I am getting undefined if I try to access this variables inside this function.

I am new to typescript, how can I access this variable inside this function?

Technology: Typescript, Angular 2, Angular 1.6.5, JavaScript

admin-company-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);

    });
}

I suspected it can be used by .bind(this) but I am not that familiar with where to add .bind();

https://angular.io/guide/http for ref.


回答1:


Make use of Arrow function which preserves the value of 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);
    });


来源:https://stackoverflow.com/questions/45295467/how-to-access-this-variable-inside-this-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!