1

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.

0

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that's it, now I can access to sessions (but apparently not to their content, but I'd say this is unrelated to this question so big thanks!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.