GWorking
GWorking

Reputation: 4341

typescript in angular2, how to access class variables through this

Given this code, how can I access to the object "sessions"? it fails due to "this" being null:

/// <reference path="chrome/chrome-app.d.ts" />

import { Component, Input, OnInit } from '@angular/core';
import { AppService } from './app.service';

@Component({
    selector: 'tabs',
    templateUrl: './templates/app.html',
    providers: [ AppService ]
})

export class AppComponent implements OnInit {
    public sessions : Object;
    constructor( private appService : AppService ) {}

    getBookmarkLists() {
        console.log(this.sessions) // it gives undefined
        this.sessions['test'] = 'yea'; // it fails
        this.appService.getBookmarks().then(function(bookmarks : any) {
            console.log(this.sessions) // it fails
        });

    }

    ngOnInit() {
        this.getBookmarkLists();
    }
 }

What I would expect is to be able to access to the variable and populate it.

Upvotes: 1

Views: 1136

Answers (1)

alek kowalczyk
alek kowalczyk

Reputation: 4936

You didn't initialized this Sessions object anywhere, should be as far I know:

export class AppComponent implements OnInit {
    public sessions: Session[] = []; // You forgot here to initialize it
    constructor( private appService : AppService ) {}

    getBookmarkLists() {
        console.log(this.sessions) // no it shouldn't give undefined
        this.sessions['test'] = 'yea'; // and this shouldn't fail
        this.appService.getBookmarks().then((bookmarks : any) => {
            // this should be an arrow function or function bound to use it
            // otherwise this will point to the function itself.
            console.log(this.sessions) // it shouldn't fail
        });

    }

    ngOnInit() {
        this.getBookmarkLists();
    }
}

with the sessions = []; being the crucial part. So it's not only an issue of this which references the class instance in methods as it should.

The callback passed to the then should be an arrow function not a classic function, to keep the this reference to the class instance.

Upvotes: 5

Related Questions