ошибка объекта объекта со скриптом java и ionic - PullRequest
1 голос
/ 11 июля 2020

Я создаю мобильное приложение с данными covid19 в реальном времени. Я использовал api. но у меня нет доступа к данным json. при запуске отображается ошибка объекта объекта. вот текущий вывод вот данные внутри api. вот данные api .

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { LoadingController } from '@ionic/angular';
import { finalize } from 'rxjs/operators';
import { NULL_EXPR } from '@angular/compiler/src/output/output_ast';


@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage {
  data : string;
  error: string;
  loading: any;
  obj: string;
  updatedDateSL: string;
  

  constructor(private http: HttpClient,public loadingController: LoadingController) {
    this.data='';
    this.error='';
    this.obj='';
    this.updatedDateSL='';
    
  }
  
 async ionViewWillEnter() {
    await this.presentLoading();
    // Load the data
    this.prepareDataRequest()
   .pipe(
      finalize(async () => {
          // Hide the loading spinner on success or error
          await this.loading.dismiss();
      })
  )
      .subscribe(
         data=> {                                                                         //data is a java script object that is why it can stringfy.
          //updatedDateSL = data.data.update_date_time;                                   // Set the data to display in the template
          this.data = JSON.stringify(data);                                              //converts to string 
          this.obj=JSON.parse(this.data);                                                //info is a javascript objct
            
            
            //var totCasesSL = info.data.local_total_cases;
            //var totHospitalSL = data.local_total_number_of_individuals_in_hospitals;
            //var totRecoverSL = data.local_recovered;
            //var totDeathSL = data.local_deaths;
            //var newSL = data.local_new_cases;
            //var newDeathSL = data.local_new_deaths;
            //var totActiveSL = data.local_active_cases;   
            //alert(info.update_date_time);
        },
        err => {
          // Set the error information to display in the template
          this.error = `An error occurred, the data could not be retrieved: Status: ${err.status}, Message: ${err.statusText}`;
        }
      );
  }

  async presentLoading() {
    // Prepare a loading controller
    this.loading = await this.loadingController.create({
        message: 'Loading...'
    });
    // Present the loading controller
  await this.loading.present();
}

  private prepareDataRequest(): Observable<object> {
    // Define the data URL
    
    //const dataUrl = 'https://api.nigelbpeck.com/';
    const dataUrl = 'https://hpb.health.gov.lk/api/get-current-statistical/';
    // Prepare the request
    return this.http.get(dataUrl);
  }
  
  
}

здесь - это файл html.

/<ion-header>
  <ion-toolbar>
    <ion-title>
      Ionic 4 Example App
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>

  <div class="ion-padding">
    <p>Data will be presented here...</p>
    <p *ngIf="!error;else errorContent">{{ obj ? obj : '-' }}</p>
     <ng-template #errorContent><p><span style="color: red;">{{error}}</span></p></ng-template>
    

     
  </div>
</ion-content>

Мне нужно получить local_new_cases и local_total_cases.Api connction работает здесь, это событие, при котором я запускаю приложение успешно. окончательный успешный вывод.

1 Ответ

1 голос
/ 11 июля 2020

Чтобы отображать данные в html, вам необходимо преобразовать данные в строку, поэтому вы должны использовать data вместо obj в html. Обновите код html с

<ion-content>
  <div class="ion-padding">
    <p>Data will be presented here...</p>
    <p *ngIf="!error;else errorContent">{{ obj ? obj : '-' }}</p>
     <ng-template #errorContent><p><span style="color: red;">{{error}}</span></p></ng-template>
  </div>
</ion-content>

до

<ion-content>
  <div class="ion-padding">
    <p>Data will be presented here...</p>
    <p *ngIf="!error;else errorContent">{{ data ? data : '-' }}</p>
     <ng-template #errorContent><p><span style="color: red;">{{error}}</span></p></ng-template>
  </div>
</ion-content>
...