解析JSON数据仅适用于模板(HTML),不适用于组件类(Typescript) [英] Parsing JSON Data working only for template(HTML) but not for Component Class(Typescript)

查看:62
本文介绍了解析JSON数据仅适用于模板(HTML),不适用于组件类(Typescript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析一个 json 文件以使用,并提取数据.

I would like to parse a json file to use, and extract data.

我不知道为什么从我的代码中提取的数据仅适用于我的html,而对于我的打字稿代码却为空...

I don't know why the data extracted from my code work only for my html, but is empty for my typescript code...

要解析的json文件:

json file to parse :

[
  {
    "appleWatch": "generation_3",
    "bracelets": ["model_1","model_2","model_3"]
  },
  {
    "appleWatch": "generation_4",
    "bracelets": ["model_1","model_4","model_5"]
  }
]

我的组件的打字稿:

export class AppleKitComponent implements OnInit {
  constructor(private httpService: HttpClient) {}

  arrAppleWatch: AppleWatchModel[] = [];
  selectedWatch: AppleWatchModel = null;
  url = '../../assets/json/appleKit.json';

  ngOnInit() {
    this.arrAppleWatch = this.parseAppleWatchData();
    console.log(this.arrAppleWatch.toString() + 'test');
  }

  parseAppleWatchData() {
    this.httpService.get('../../assets/json/appleKit.json').subscribe(
      data => {
        this.arrAppleWatch = data as AppleWatchModel[]; // FILL THE ARRAY WITH DATA.
      },
      (err: HttpErrorResponse) => {
        console.log(err.message);
      }
    );
    return this.arrAppleWatch;
  }
}

我的appleWatch模型:

My appleWatch model :

export class AppleWatchModel {
  constructor(
    public watch: string,
    public bracelets?: string[],
    public bracelet?: string
  ) {
  }
}

HTML:

{{arrAppleWatch |json }}

我的日志应该输出:

[{"appleWatch":"generation_3",手镯":["model_1","model_2","model_3"]},{"appleWatch":"generation_4",手镯":["model_1," model_4," model_5]}]

但是它只是打印一个空字符串.

but it just prints an empty string.

我的html工作并显示数组:

My html work and show the array :

[ { "appleWatch": "generation_3", "bracelets": [ "model_1", "model_2", "model_3" ] }, { "appleWatch": "generation_4", "bracelets": [ "model_1", "model_4", "model_5" ] } ]

推荐答案

您的实现存在一些问题.

There are a few issues with your implementation.

httpService.get 调用将是 async 调用.因此,它不会立即为您提供数据.但是您正在尝试立即访问它.因此,您没有在Component Class中得到它.

The httpService.get call call would be an async call. So it won't give you the data instantly. But you're trying to access it instantly. Hence you're not getting it in the Component Class.

尝试一下:

import { Component } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

export interface AppleWatchModel {
  watch: string;
  bracelets?: string[];
  bracelet?: string;
};

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private httpService: HttpClient) {
  }

  arrAppleWatch: AppleWatchModel[] = [];
  selectedWatch: AppleWatchModel = null;

  ngOnInit() {
    this.parseAppleWatchData()
      .subscribe(res => {
        this.arrAppleWatch = res;
        console.log('test: ', this.arrAppleWatch);
      });
  }

  parseAppleWatchData() {
    return this.httpService.get<AppleWatchModel[]>('/assets/appleKit.json');
  }
}

在这里,我们从 parseAppleWatchData 返回一个 Observable< AppleWatchModel []> .因此,我们可以在 ngOnInit 中对其进行 subscribe 以获得实际数据.

Here, we're returning an Observable<AppleWatchModel[]> from parseAppleWatchData. So we can subscribe to it in the ngOnInit to get the actual data.

这是一个 工作样本StackBlitz 供您参考.

这篇关于解析JSON数据仅适用于模板(HTML),不适用于组件类(Typescript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆