Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

angular - Function implementation is missing or not immediately following the declaration, TypeScript class

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...