3

I'm having trouble with a .net core SPA app. - Results are being passed back by the API call - the SPA is not handling the results.

here is the pertinent code:

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;
}

and the console results when RunTests() is fired:

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

As far as I can tell, I'm getting valid json back from the API (indicated by console.log spitting it out, but it is not actually building the object which results in the undefined.

3 Answers 3

1

I think your properties in the JSON are parsed from upper case to lower case - CheckName -> checkName. As Javascript/Typescript is a case sensitive language you need to different property names.

Try to log with lower case and also change your property names to start with lower case. It is a common standard in Javascript/Typescript to start function and variable/property names via lower case.

console.log(this.testResults.checkName);
Sign up to request clarification or add additional context in comments.

Comments

1

You are getting undefined because this console.log(this.testResults) is fired first

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']);
    });
  }

or use SetTimeOut

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

        });
      }

Comments

0

I had a similar issue i.e. it looked lika valid json response but in fact it was a "text" response. Give the following a try:

  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'
    });
  }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.