【问题标题】:ionic 3 doesn't showing data json in htmlionic 3 不在 html 中显示数据 json
【发布时间】:2018-08-29 15:24:13
【问题描述】:

我正在开发使用 json 文件的应用程序,它可以在本地服务器上完美运行,但不显示来自 API Json 的天气数据。

代码如下:

RedditData.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

@Injectable()
export class RedditData {
    private url : string = "http://api.wunderground.com/api/d8585d80376/lang:AR/conditions/geolookup/q/ormm.json";
    constructor(public http: HttpClient) {
        console.log('Hello RedditData Provider');
    }

    getRemoteData(){

        return this.http.get(this.url)



    }
    }

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { RedditData } from '../../providers/reddit-data/reddit-data';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

    weather: any={};

    constructor(public navCtrl: NavController, public redditService: RedditData) {
    }

    ionViewDidLoad(){
        this.redditService.getRemoteData()
        .subscribe(weather => {
         console.log(weather)
         this.weather.current_observation;

    });
    }

    }

代码在控制台中运行良好,没有任何错误,但 html 中没有信息

<ion-header >
  <ion-navbar color="primary">
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding *ngIf="weather">
   <p > {{weather.observation_time}}</p>

</ion-content>

【问题讨论】:

    标签: ionic-framework ionic3


    【解决方案1】:

    您没有将数据分配给组件属性:

        ionViewDidLoad(){
            this.redditService
                .getRemoteData()
                .subscribe((weather: any) => {
                     console.log(weather)
                     this.weather = weather.current_observation; // <-- here!
            });
        }
    

    【讨论】:

    • 当我更改您的答案时,我收到错误“对象”类型上不存在属性“current_observation”。你可以看到json响应jsoneditoronline.org/?id=c9c13844c0df4d2b83cc9f68b5b2384b
    • 我建议为该响应创建一个类,但与此同时,您可以将响应 castany 类型,并且该错误应该消失.我已经更新了答案。
    • 工作正常,谢谢。我有疑问,当我们放置(无论是:任何)它的对象时,对吗?在那种情况下我们不能用于数组?
    • anyanything,它可以是一个对象、一个数组等等……如果你想将它指定为任何东西的数组,你可以使用Array&lt;any&gt;
    猜你喜欢
    • 2017-12-12
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 2019-11-03
    • 2023-04-08
    • 2016-11-09
    • 2020-06-18
    相关资源
    最近更新 更多