Angular 如何在静态对象中调用类函数?

Angular 如何在静态对象中调用类函数?,angular,typescript,Angular,Typescript,例如: export class cls1{ str1:string; constructor(s:string){ this.str1 = s; } func1(){ return "hello " + this.str1; } } export class AppComponent { static obj2:cls1= JSON.parse(`{"str1":"efgh"}`); AppComponent.obj2.func1(); //

例如:

export class cls1{
  str1:string;

  constructor(s:string){
    this.str1 = s;
  }

  func1(){
    return "hello " + this.str1;
  }
}

export class AppComponent  {

static obj2:cls1= JSON.parse(`{"str1":"efgh"}`);

AppComponent.obj2.func1(); //  func1 is not a function
}
问题是静态对象中的函数成员不熟悉。
我得到一个错误:func1不是一个函数

你到底想在这里做什么?这看起来不像我能想到的任何用例。或者你只是在胡闹,试着用打字稿?一个函数如何从一个只包含一个对象的
JSON.parse
调用中神奇地出现

无论如何,我能想到的最接近该函数工作的方法是将代码更改为:

class cls1{
  str1:string;

  constructor(s:string){
    this.str1 = s;
  }

  func1(){
    alert(this.str1);
  }
}

class AppComponent  {

   static obj2:cls1= new cls1(JSON.parse('{"str1":"efgh"}').str1);
}

AppComponent.obj2.func1(); // alert: 'efgh'


让我们暂时忽略编码风格错误,然后开始吧:)

我不是角度专家,但obj2似乎是这里的一个实例,因此您无法调用该方法。尝试cls1.func1()谢谢,但是cls1不是静态的,所以每次有实例时它都不存在。谢谢,例如JSON.parse就是jast。我有一个非常大的静态对象,它有很多成员和函数,我想打开现有成员的值,你的代码接受错误:(SystemJS)cls1不是一个构造函数。好的,在typescript中它是工作的,但我在angular2-typescript中工作,它被接受的错误是:“(SystemJS)cls1不是一个构造函数”:-(这是因为您可能缺少某个导入。您使用的是IDE吗?是的,我使用的是WebStorm。