【问题标题】:Function implementation is missing or not immediately following the declaration, TypeScript class声明、TypeScript 类后缺少或未立即执行函数实现
【发布时间】:2023-03-31 04:01:01
【问题描述】:

我有一个手写数组来填充我班级的一张桌子,现在我得到了这个数组 来自 ngOnInit 上的 JSON 的内容,但它的结构不是我需要的。

所以我正在尝试编写一个函数来用我在 ngOnInit 上得到的这个新数组填充表格数组。

问题是,当我在我的 TS 类中的函数之外编写代码时,我收到此错误“函数实现丢失或未立即在声明之后”。

为什么会这样?可以做些什么来解决这个问题?

TS

export class MyComponent implements OnInit {
    users: Object;

    constructor(private tstService: MyComponentService) { this.source = new LocalDataSource(this.data) }

    ngOnInit(): void {
        this.tstService.getTstWithObservable()
        .map(result => result.map(i => i.user.data))
        .subscribe(
           res => { this.users = res; }
       );
    }

    console.log(this.users); // Here, just an example. Throws 'Function implementation is missing or not immediately following the declaration'

    data = [
        {
          title: 'Monthly',
          sdate: '01/04/1990',
          edate: '30/09/1990',
        },
      ];

    source: LocalDataSource;
}

【问题讨论】:

  • 认为解释已经足够了。刚刚编辑了OP。问题是我在函数或 ngOnInit 之外编写的任何内容都会引发上述错误。
  • 尝试在构造函数(数据和源)之前声明变量。

标签: angular function typescript class declaration


【解决方案1】:

这里的问题是您在“可执行区域”(例如ngOnInit 内的“区域”)之外有一些“代码执行”(console.log(this.users);)。

如果您需要执行console.log(this.users); 以查看devtools 中的数据,您应该将console.log 部分移动到ngOnInit 内,这是您的类MyComponent 的可执行部分,或者可能在@ 内987654328@.

我建议你这样做:

ngOnInit(): void {
    this.tstService.getTstWithObservable()
    .map(result => result.map(i => i.user.data))
    .subscribe(
       res => {
                this.users = res;
                console.log(this.users); // <-- moved here!
       }
   );
}

问题是您尝试执行的代码需要在 Angular 执行的某个方法中。

请参阅this demo 的一些示例。相关代码如下:

export class AppComponent  implements OnInit{
  name = 'Angular 6';

  constructor() {
    console.log(name); // OK
  }

  ngOnInit() {
    console.log('sample not giving error'); // OK
  }

 // comment line below and the error will go away
  console.log(name); // this will throw: Function implementation is missing or not immediately following the declaration
}

【讨论】:

  • 刚刚意识到这一点!谢谢解释
猜你喜欢
  • 1970-01-01
  • 2021-10-05
  • 2016-09-19
  • 2014-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多