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.

3
  • you could use the arrow function expression, which preserves the value of this. make use of () => { } function instead of function . Commented Jul 25, 2017 at 6:30
  • Is it normal that your code is outside any method and that your class is not closed properly ? Commented Jul 25, 2017 at 6:30
  • 3
    Possible duplicate of How to access the correct `this` inside a callback? Commented Jul 25, 2017 at 6:40

1 Answer 1

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);
    });
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.