给定此代码,我如何访问对象“会话”?由于“ 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();
}
}
我希望能够访问并填充变量。
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
对类实例的引用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句