Function implementation is missing or not immediat

2020-04-08 12:08发布

问题:

I got a handwritten array to fill a table in my class, now I'm getting this array's content from a JSON on ngOnInit but it's not structured as I need.

So I'm trying to write a function to fill the table array with this new one I'm getting on ngOnInit.

The issue is that when I write code outside of a function in my TS class I get this error "Function implementation is missing or not immediately following the declaration".

Why is that and what can be done to fix this?

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;
}

回答1:

The issue here is that you have some "code execution" (console.log(this.users);) outside an "executable area" (for instance the "area" inside the ngOnInit).

If you need to do console.log(this.users); in order to see the data in the devtools, you should move the console.log part inside the ngOnInit which is an executable part of you class MyComponent or maybe inside the constructor.

I would recommend you to do it like this:

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

The thing is the code you're trying to execute needs to be inside some method which Angular executes.

See this demo with some examples. The relevant code is below:

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
}