2017-01-07 71 views
1

鑑於此代碼,我如何訪問對象「會話」?它由於「this」失效而失敗:typescript in angular2,如何通過此訪問類變量

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

我期望的是能夠訪問變量並填充它。

回答

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應該是一個箭頭的功能不是經典功能的回調,保持this參考類的實例。

+0

是的,就是這樣,現在我可以訪問會話(但顯然不是他們的內容,但我會說這與這個問題無關,所以非常感謝!) – Gerard