如何获取Angular中Observable的特定字段?

How to get specific fields of Observable in Angular?

我目前正在使用 OpenWeatherMap API (https://openweathermap.org/current),我正在尝试获取 main.tempmain.feels_likemain.temp_minmain.temp_max 我从 HTTP 请求中获得的 Observable 字段。

我可以获取所有数据,但我只需要这些字段。如何获取这些字段并将它们放入我自己的变量中?

import {Component, OnInit} from '@angular/core';
import {WeatherServiceService} from "./Services/weather-service.service";
import {LocationData} from "./models/location-data";
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";

declare const L: any
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

data!:LocationData
location!:string
locationData = new LocationData();

constructor(public weatherService:WeatherServiceService, public http: HttpClient) {
}

ngOnInit() {
if (!navigator.geolocation){
  console.log("location is not supported")
}
navigator.geolocation.getCurrentPosition((position) => {
  const coords = position.coords
  const latLong = [coords.latitude, coords.longitude]
  console.log(
    'lat: ${position.coords.latitude}, lon: ${position.coords.longitude}'
  );
  let mymap = L.map('map').setView(latLong, 13);

  L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}? access_token=pk.eyJ1Ijoia29lbnRlcmhlZWdkZSIsImEiOiJja3NpejZibWsxcGFhMzBvZjRlOXhkcWZoIn0.Bs552hPcijlBy1b2kDqfvw', {
    attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
    maxZoom: 18,
    id: 'mapbox/streets-v11',
    tileSize: 512,
    zoomOffset: -1,
    accessToken: 'your.mapbox.access.token'
  }).addTo(mymap);

  let marker = L.marker(latLong).addTo(mymap);
});
this.watchPosition();
}

watchPosition(){
let desLat = 0;
let desLon = 0;
let id = navigator.geolocation.watchPosition(position => {
  console.log(
    'lat: ${position.coords.latitude}, lon: ${position.coords.longitude}'
  );
  if (position.coords.latitude === desLat && position.coords.longitude === desLon){
    navigator.geolocation.clearWatch(id);
  }
}, (err) => {
  console.log(err);
}, {
  enableHighAccuracy: false,
  timeout: 5000,
  maximumAge: 0
})
}

getCoordinates(){

this.weatherService.getData().subscribe((data: LocationData) => this.locationData = {
  temp_min: data.temp_min,
  temp_max: data.temp_max,
  temp: data.temp,
  feels_like: data.feels_like
})

// this.weatherService.getData().subscribe(data => this.locationData = data)

// this.weatherService.getData().subscribe(res =>{
//   console.log(res)
// })



}

}

接口:

import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import {LocationData} from "../models/location-data";

@Injectable({
providedIn: 'root'
})
export class WeatherServiceService {

constructor(public http: HttpClient) {

}

getData() : Observable<LocationData>{
return this.http.get<LocationData>('http://api.openweathermap.org/data/2.5/weather?q=Enschede&appid=2a47a80c223baab80003883c31f35729')

}
}

型号:

export class LocationData {
temp!:number
feels_like!:number
temp_min!:number
temp_max!:number

}

看起来您几乎已经拥有所需的一切,在您的服务中,您可以 map 响应以仅获取您想要的值,如下所示:

这是 json 响应的结构:

getData() : Observable<LocationData>{
  const url = 'http://api.openweathermap.org/data/2.5/weather?q=Enschede&appid=2a47a80c223baab80003883c31f35729';
  return this.http.get(url).pipe(map((response: any) => ({
    temp: response.main.temp,     
    temp_min: response.main.temp_min, 
    temp_max: response.main.temp_max,
    feels_like: response.main.feels_like
  })))
}

然后你就可以订阅你的组件

getCoordinates() {

  this.weatherService.getData().subscribe((data: LocationData) => {
    this.locationData = data;
  });

  // this.weatherService.getData().subscribe(res =>{
  //   console.log(res)
  // })
}