我有一个手写数组来填充我的类中的一个表,现在我得到了这个数组的 来自 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;
}
这里的问题是你在"可执行区域"(例如ngOnInit
内的"区域")之外有一些"代码执行"(console.log(this.users);
)。
如果您需要执行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!
}
);
}
问题是你尝试执行的代码需要位于 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
}