【问题标题】:How do I pass data from a json file into a html file in Angular 2?如何将 json 文件中的数据传递到 Angular 2 中的 html 文件中?
【发布时间】:2017-02-26 00:15:29
【问题描述】:

我有这个文件。

wordCloud.ts

export class HomePageComponent {
wordcloudData : Array<string>;
private searchField : string;
private wordsApi : string;
wordClouds: any[] = [];
errorMessage: string;
listId:any = 1;

@Input() data : any;
@Input() testProperty : any;
@Input() dataField : string;
@Input() apiUrl :  string;


constructor(public wordCloudListService: LexiconListService) {}

getWordCloudList() {
this.wordCloudListService.get('/assets/adhoc-search.json')
                .subscribe(
                    wordClouds => {
                        EmitterService.get(this.listId).emit(wordClouds);
                    },
                    error =>  this.errorMessage = <any>error
                );
                }



ngOnInit() {
    this.getWordCloudList();
    EmitterService.get(this.listId).subscribe((wordClouds:any) => {this.wordClouds});

}

}

wordCloud.html

<div class="center" style="margin:  0 auto; width:  30%; padding-top: 100px;">
    <cst-word-cloud [data]="{{wordClouds}}"></cst-word-cloud>
</div>

如您所见,我正在尝试加载 json 数据并将数据显示到 wordCloud hmtl 中。我目前在执行此操作时遇到困难?有什么我做错了吗?如何传递 wordClouds 数组中的值来显示它?

【问题讨论】:

    标签: html json angular typescript


    【解决方案1】:

    在您的ngOnInit() 中,您没有在this.wordClouds 中获取wordClouds 的数据.. 这样做。

         ngOnInit() {
                 this.getWordCloudList();
                 EmitterService.get(this.listId)
                      .subscribe((wordClouds:any) => {
                                                       this.wordClouds = wordClouds;
                                                  });
            }
    

    【讨论】:

    • 感谢您的回复!澄清一下,既然您已经将this.wordCloudListService.get('/assets/adhoc-search.json') 替换为EmitterService.get(this.listId),它怎么知道json 是从哪里加载的?
    • 我不是说要改成getWordCloudList(),请注意我改成ngOnInit()
    • 不幸的是,没有数据被加载到函数中。这有什么原因吗?
    【解决方案2】:

    不发出数据。首先是发出数据不是正确的方法。您应该始终发出用于临时基础的布尔值或数据等状态。我宁愿不发出数据,而是先存储。将其存储在某个数据存储/类文件中。创建一个类并将数据存储在其中。从该类 getter 方法存储绑定模板后。

    【讨论】:

    • 感谢您的回复!我会探索你所说的:)干杯!
    猜你喜欢
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    相关资源
    最近更新 更多