函数实现缺失或没有紧跟在声明之后,TypeScript 类

pre*_*vox 8 class declaration function typescript angular

我有一个手写数组来填充我班上的表格,现在我从 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;
}
Run Code Online (Sandbox Code Playgroud)

lea*_*iro 10

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

如果你需要做console.log(this.users);才能看到devtools的数据,你应该移动的console.log内部部分ngOnInit是你的类的可执行部分MyComponent或者也许里面 constructor

我建议你这样做:

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

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

请参阅此演示并附上一些示例。相关代码如下:

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
}
Run Code Online (Sandbox Code Playgroud)