问题描述: 在Angular 6中,使用json对象管道时,无法正确显示数据。
解决方法:
import { JsonPipe } from '@angular/common';
@NgModule({
declarations: [
...
JsonPipe,
...
],
...
})
export class AppModule { }
{{ data | json }}
ng generate pipe json
然后在生成的json.pipe.ts文件中编写以下代码:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'json'
})
export class JsonPipe implements PipeTransform {
transform(value: any): string {
return JSON.stringify(value, null, 2);
}
}
最后,在组件的模板文件中使用自定义的json管道来显示数据:
{{ data | json }}
这样就可以正确显示JSON数据了。