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.

1
  • 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!)
    – GWorking
    Jan 7, 2017 at 2:19

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.