0

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.

spacedev
  • 1,086
  • 13
  • 13
  • you could use the arrow function expression, which preserves the value of this. make use of `() => { }` function instead of function . – Rahul Singh Jul 25 '17 at 06:30
  • Is it normal that your code is outside any `method` and that your `class` is not closed properly ? – ADreNaLiNe-DJ Jul 25 '17 at 06:30
  • 3
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – AT82 Jul 25 '17 at 06:40

1 Answers1

8

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);
    });
Rahul Singh
  • 19,030
  • 11
  • 64
  • 86