Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
Cómo extraer solo ciertos campos del objeto de respuesta Http

Soy bastante nuevo en Angular y estoy tratando de obtener solo ciertos valores del objeto de respuesta Http.

En mi servicio, estoy haciendo una solicitud de obtención para obtener datos meteorológicos para una ciudad determinada de la siguiente manera:

 export class CityService { private baseUrl = 'https://api.openweathermap.org'; constructor(private http: HttpClient) { } getCity(name: string){ return this.http.get(`${this.baseUrl}/data/2.5/weather?q=${name}&appid=${environment.weatherApiKey}`); } }

Ahora, en el componente, cierro la sesión de la respuesta así:

 ngOnInit(): void { this.cityService.getCity('lucija').subscribe(data => { console.log(data) }); }

La respuesta en sí es solo un objeto con muchos campos (también anidados), que la mayoría de ellos no necesito.

También configuré una interfaz en la que me gustaría "guardar" en ciertos campos de respuesta:

 export interface City { name: string; description: string; icon: string; main: object; search: string; }

¿Cómo puedo hacer eso? ¡Salud!

EDITAR: según la respuesta a continuación, obtuve 2 errores, que resolví así:

 getCity(name: string): Observable<City>{ return this.http.get(`${this.baseUrl}/data/2.5/weather?q=${name}&appid=${environment.weatherApiKey}`) .pipe(map((res: any) => <City>{ name: res.name, description: res.weather[0].description, icon: `http://openweathermap.org/img/w/${res.weather[0].icon}.png`, main: res.main, search: name }));
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Una solución podría ser mapear el objeto en su servicio. Entonces su servicio devolverá el Objeto de Ciudad.

 export class CityService { private baseUrl = 'https://api.openweathermap.org'; constructor(private http: HttpClient) { } getCity(name: string): Observable<City>{ return this.http.get(`${this.baseUrl}/data/2.5/weather?q=${name}&appid=${environment.weatherApiKey}`) .pipe(map((res) => { return { name: res.cityName }; }); // only added name as example. In the final code map all the values to the correct City field. } }

Si no desea que su servicio devuelva siempre el objeto Ciudad, puede realizar esta asignación en su componente.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!