angular2中的typescript,如何通过这个访问类变量

时间:2017-01-07 01:39:26

标签: javascript angular typescript this

鉴于此代码,我如何访问对象“会话”?它由于“this”为空而失败:

/// <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();
    }
 }

我期望能够访问变量并填充变量。

1 个答案:

答案 0 :(得分:5)

你没有在任何地方初始化这个Sessions对象,应该是我所知道的:

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();
    }
}

sessions = [];是关键部分。 所以它不仅是this的问题,它在方法中引用了类实例。

传递给then的回调应该是箭头函数而不是经典函数,以保持对{1>}类实例的引用。