Angular / Ionic Observer и Observable - PullRequest
0 голосов
/ 15 мая 2018

Я не знаю после прочтения страниц и страниц документа «Обозреватели», как им манипулировать. Я просто хотел бы вывести на экран погоду дня с помощью внешнего API. Проблема в том, что я получил Observable своего класса, но ничего не получилось.

Это мой провайдер для получения информации от API:

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

import { Observable } from "rxjs/Rx";
import { Http, Response } from "@angular/http";


@Injectable()
export class OpenWeatherProvider {
  apikey = 'ea91a7eab8e8b73b433086eb0244fc94';
  WeatherArr: Array<String> = [];


  constructor(public http: HttpClient) {

  }

  getWeatherPerLatLng(lat,lng) {
    return this.http.get<Weather>('http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+lng+'&units=metric&appid='+ this.apikey);
  }
}

export interface Weather{
  coord: {
    lon: number,
    lat: number
  },
  weather: [
    {
      id: number,
      main: String,
      description: String,
      icon: String
    }
  ],
  base: String,
  main: {
    temp: number,
    pressure: number,
    humidity: number,
    temp_min: number,
    temp_max: number
  },
  visibility: number,
  wind: {
    speed: number,
    deg: number
  },
  clouds: {
    all: number
  },
  dt: number,
  sys: {
    type: number,
    id: number,
    message: number,
    country: String,
    sunrise: number,
    sunset: number
  },
  id: number,
  name: String,
  cod: number
}

и это мой geoloc.ts, чтобы показать информацию:

import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';

 // importation des plugins
import { Geolocation } from '@ionic-native/geolocation';
import { OpenWeatherProvider, Weather } from '../../providers/meteo/open-weather-provider'
import { Test } from '../test/test';
import { Subscription } from 'rxjs/Subscription';
import { Observable } from "rxjs/Rx"

@Component({
  selector: 'geoloc',
  templateUrl: 'geoloc.html'
})
export class Geoloc {   
    public lng = 0;
    public lat = 0;
    public loading: boolean = false;
    public weather$ : Observable<Weather>;

  constructor(public navCtrl: NavController, private geolocation: Geolocation, public platform: Platform, public Pro: OpenWeatherProvider) {
        platform.ready().then(() =>{
              this.loadPosition();
              const component = this;
        });
    }

    loadPosition(){
        this.geolocation.getCurrentPosition().then((resp) => {
        // resp.coords.latitude
        //let userPosition: LatLng = news LatLng(resp.coords.latitude,resp.coords.longitude);
        //console.log(resp.coords.latitude + ' ' + resp.coords.longitude);\
        this.lng = resp.coords.longitude;
        this.lat = resp.coords.latitude;
        this.weather$ = this.Pro.getWeatherPerLatLng(this.lat,this.lng);

        console.log('Demande de GetWeatherPerLatLng',this.weather$);
        });
    }

}

И HTML для взаимодействия:

<ion-header>
    <ion-navbar>
        <button ion-button menuToggle>
            <ion-icon name="menu"></ion-icon>
          </button>
      <ion-title>Geolocalisation</ion-title>
    </ion-navbar>
  </ion-header>

  <ion-content padding>
    <h2>{{ 'GPS' | translate}}</h2>
    <p>
      Latitude {{ lat }}, Longitude{{ lng }}
    </p>
    <p >
      <a href="../test/test.html">{{ 'MAPS' | translate}}</a>
    </p>
    <br/>
    <p>Country: {{weather$}}</p>
    <p></p>


</ion-content>

Когда я звоню {{weather$}}, на экране отображается: *Country: object Objects..*

Вот экран, который я вижу с console.log

CONSOLE PICTURE

1 Ответ

0 голосов
/ 16 мая 2018

Когда я звоню {{weather $}}, на экране отображается: Страна: объект Объекты ..

Вы печатаете наблюдаемое, а не данные.

Если вы хотите напечатать наблюдаемые данные в html, вы можете использовать async pipe.

Чтобы напечатать весь объект данных, выполните:

{{weather$ | async}}

InЧтобы просмотреть и распечатать свойство, выполните:

{{(weather$ | async)?.base}}

Вышеуказанный недостаток имеет недостаток, заключающийся в том, что вы должны продолжать подписываться на каждое свойство.Лучшая техника:

<div *ngIf="weather$ | async as weather">
    {{weather.base}}
    <!-- other properties of weather -->
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...