Brak implementacji funkcji lub nie następuje ona bezpośrednio po deklaracji klasy TypeScript


Mam odręczną tablicę do zapełnienia tabeli w mojej klasie, teraz otrzymuję
zawartość tej tablicy pochodzi z formatu JSON do ngOnInit, ale nie ma takiej struktury, jakiej potrzebuję.
Więc próbuję napisać funkcję, która zapełni tablicę tabel tą nową funkcją, którą otrzymuję na ngOnInit.
Problem polega na tym, że kiedy piszę kod poza funkcją w mojej klasie TS, pojawia się ten błąd „Brak implementacji funkcji lub jej brak bezpośrednio po deklaracji”.
Dlaczego tak się dzieje i co można zrobić, aby to naprawić?
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;
}

Zaproszony:
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Problem polega na tym, że masz pewne „wykonanie kodu” (
console.log (this.users);
) poza „obszarem wykonywalnym” (na przykład „obszar” wewnątrz
ngOnInit ). 
Jeśli musisz wykonać
console.log (this.users);
, aby zobaczyć dane w devtools, musisz przenieść część
console.log
do środka
ngOnInit
, która jest wykonywalną częścią klasy
MyComponent
lub prawdopodobnie wewnątrz
konstruktora
.
Poleciłbym zrobić to w ten sposób:
ngOnInit(): void {
this.tstService.getTstWithObservable()
.map(result => result.map(i => i.user.data))
.subscribe( res => {
this.users = res;
console.log(this.users);// <-- moved here!
}
);
}

Chodzi o to, że kod, który próbujesz wykonać, musi znajdować się wewnątrz jakiejś metody, którą wykonuje Angular.
Spójrz
to demo
https://stackblitz.com/edit/an ... nt.ts

z kilkoma przykładami. Odpowiedni kod podano poniżej:
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
}

Aby odpowiedzieć na pytania, Zaloguj się lub Zarejestruj się