首页 > 解决方案 > 在角度打字稿中从控制台访问类方法

问题描述

我需要通过控制台调用类方法,该控制台实习生访问类变量,然后反映在 HTML 上。我推荐从 Angular 6 的浏览器控制台调用服务功能,但我无法访问此关键字。

export class AppComponent {
    title = 'calender-app';
    timeslot: any =  [];

    constructor(){
      window['plotEvent'] = this.plotEvent;
    }
  
    plotEvent(events: Calender[]): void{
    // not able to access this.timeslot when I call it from browser's console.
    this.timeslot.push(...events); // getting error as can't read property timeslot of undefined.
    }

标签: angulartypescript

解决方案


我假设您正在尝试访问浏览器控制台上的 typescript 方法。

您可以通过添加或在以下内容中使整个 angularcomponent.ts的变量、方法等可在浏览器控制台中访问:OnInitconstructor

假设您正在尝试访问 中的方法AppComponent,您就去吧。

OnInit() {
    window['AppComponent'] = this;
}

或者:

constructor() {
    window['AppComponent'] = this;
}

服务也是如此。

然后在控制台中你去: AppComponent.myMethod()


推荐阅读