【问题标题】:Angular 6 - Parsing JSONAngular 6 - 解析 JSON
【发布时间】:2019-01-17 17:08:01
【问题描述】:

我在使用 .net 核心 SPA 应用程序时遇到问题。 - 结果由 API 调用传回 - SPA 不处理结果。

这里是相关代码:

SPA ts:

class TestLibraryItem {
  private _apiPath: string;
  private _http: HttpClient;

  public name: string;
  public testResults: TestResult;

  constructor(name: string, apiPath: string, http: HttpClient) {
    this.name = name;
    this._apiPath = apiPath;
    this._http = http;
  }

  RunTests() {
    this._http.get<TestResult>(this._apiPath)
      .subscribe(result => {
      this.testResults = result;
      console.log(this.testResults);
      console.log(this.testResults.CheckName);
    });
  }
}

class TestResult {
  CheckName: string;
  Checks: CheckResult[];
}

class CheckResult {
  Test: string;
  Pass: boolean;
}

以及触发 RunTests() 时的控制台结果:

{"CheckName":"Check One","Checks":[{"Test":"Test one","Pass":true},{"Test":"Test two","Pass":true}]}
undefined

据我所知,我从 API 中获取了有效的 json(由 console.log 吐出表示,但它实际上并没有构建导致未定义的对象。

【问题讨论】:

    标签: json angular asp.net-core-webapi


    【解决方案1】:

    我认为 JSON 中的属性是从大写转换为小写的 - CheckName -&gt; checkName。由于 Javascript/Typescript 是区分大小写的语言,因此您需要使用不同的属性名称。

    尝试以小写形式记录,并将您的属性名称更改为以小写形式开头。 Javascript/Typescript 中的通用标准是以小写开头的函数和变量/属性名称。

    console.log(this.testResults.checkName);
    

    【讨论】:

      【解决方案2】:

      因为这个 console.log(this.testResults) 首先被触发,所以你得到了 undefined

      RunTests() {
          this._http.get<TestResult>(this._apiPath)
            .subscribe(result => {
            this.testResults = result;
            console.log(this.testResults);
            console.log(this.testResults.CheckName === undefined ? '' : this.testResults['CheckName']);
          });
        }
      

      或使用 SetTimeOut

       RunTests() {
              this._http.get<TestResult>(this._apiPath)
                .subscribe(result => {
                this.testResults = result;
                console.log(this.testResults);
               setTimeout(()=>{console.log(this.testResults['CheckName'])},2000); 
      
              });
            }
      

      【讨论】:

        【解决方案3】:

        我有一个类似的问题,即它看起来像有效的 json 响应,但实际上它是一个“文本”响应。试试以下方法:

          getdData(inParams) {
            let headers = new HttpHeaders();
            headers = headers.append('Content-Type', 'application/json');
        
            // need responseType = text (non object)
            return this.http.get(environment.url, {
              headers,
              responseType: 'text'
            });
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-20
          • 2015-09-27
          • 2021-02-06
          相关资源
          最近更新 更多