The output from the map() function does not accurately represent the data returned by my REST call

Struggling with a REST call in my http.service.ts file while working with Angular version 7 and RxJS. The goal is to extract the "cod" value from a JSON response obtained from a REST call to the openweather API. However, when I add map() to extract the desired value, it doesn't work, only without map() it functions. What am I overlooking?

Here's my code snippet:

import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';

import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';


const API_URL = environment.apiURL;
const API_KEY = environment.apiKey;

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

  constructor(private http: HttpClient) { }

  public getWeather() {
    return this.http.get(API_URL + '?q=London,us&APPID=' + API_KEY).pipe(map(r => { return r; })).subscribe(value => {
    }, catchError(error => {
      return throwError(error);
    }))
  }
}

Answer №1

Make sure to include a return statement in your map() projection function:

map(r => {
  this.cod = r.cod;
  return r;
}),

Consider moving this code to the subscribe method instead of using map().

Answer №2

Initially, make sure to return the observable and subscribe to it in the relevant component. It is important to note that there is a missing return statement in the map operator. Avoid using global variables such as const cod; instead, try utilizing inner class variables. The current implementation is not functional.

public getWeather() {
    return this.http.get(API_URL + '?q=London,us&APPID=' + API_KEY).pipe(map(r => { return r.cod; })).subscribe(value => {
    }, catchError(error => {
      return throwError(error);
    }))
  }

It is advisable to subscribe in the component where it is required and unsubscribe onDestroy.

public getWeather() {
    return this.http.get(API_URL + '?q=London,us&APPID=' + API_KEY).pipe(map(r => { return r.cod; }));

Ensure that you consistently use the map function, verify the console for any errors. https://stackblitz.com/edit/angular-vz2q82 Could you provide details on where and how this method is being called?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript to Extract Keys from an Array

Is it possible to mandate the keys of an interface to come from an array of strings: For instance, consider the following array: const myArray = ['key1', 'key2']; I aim to define a new interface named MyInterface that would require al ...

Quick tip: Showing a default Font Awesome icon in Vue, Angular, or React when the desired icon is not found

Utilizing the <fa-icon> fontawesome component, I implement the library approach as follows: export const faIconsDefinitionsToRegister: IconDefinition[] = [ ...proRegularFaIcons, ...proSolidFaIcons, ...proLightFaIcons, ...proThinFaIcons, ... ...

Occasionally the CUSTOM_ELEMENTS_SCHEMA error may appear intermittently

After updating from Angular 8 to Angular 9, I encountered an error when running the application: error NG8002: Can't bind to 'text' since it isn't a known property of 'app-custom-message'. 1. If 'app-custom-message&a ...

Expand Angular Features

I'm attempting to create a box containing text. If the text exceeds 3 rows, I want to truncate it and add a "show more" button. Clicking on this button will reveal the full text and display a "show less" button. However, when I click on the button, th ...

Steer clear of encapsulating components or modifying the attributes of the encapsulating element

I am currently developing an application that involves dynamically adding components. One of the key components is a block component with the following template: <div id="{{element.id}}" class="row" [hidden]="hide"> ...

Looking for guidance on converting JS code to TypeScript? Let's tackle this TS test together!

I am facing the challenge of encapsulating a very complex SDK into a layer of code. I have attempted to utilize union and index types for this task, and below is a demo that I have created. How can I implement the bar method in TypeScript to pass the conso ...

Incorporate Font Awesome icons throughout your Angular8 application for added visual appeal

I'm currently working on a large Angular application that utilizes lazy loading modules. Throughout various components in different modules, I make use of icons from Font Awesome individually. Here is an example: In component.ts: import { faChevronD ...

The formgroup label is currently displayed in uppercase, but I would prefer it to be in title case

In the angular template below, I have noticed that even though the labels are in titlecase, they appear in uppercase when the page is rendered. This wasn't the desired outcome so I attempted to use the titlecase pipe and enclose the label text within ...

The NbDatePicker does not display certain Spanish names

One issue I'm facing is with the Nb-DatePicker component in my project. I tried using {provide: LOCALE_ID, useValue: "es-MX"} in my app.component to display it in Spanish. However, when February, April, May, August, or December are selected, ...

The process of upgrading all dependencies to a particular version

I need guidance on upgrading a project from Angular 6 to version 7. The challenge lies in updating numerous dependencies as well. Most tutorials available only cover upgrading to the latest version (v8), rather than a specific one. Can anyone provide ins ...

Differences Between Angular 2 RC5 ngModules and Barrels

We are currently transitioning our project from Angular 2 RC4 to RC5. One important question arises: now that ngModules have been introduced, will barrels (index files) become obsolete? Can both be utilized simultaneously? How should we go about utilizin ...

The "rest" variable is automatically assigned the type of "any" because it lacks a specified type and is used within its own initializer

Attempting to set up a private route using react router 4 and Typescript. Check out the code I'm working with: type CustomRouteProps<T> = T & { component: any, authRequired: boolean }; function PrivateRoute({ component: Component, authRequ ...

Angular 8 ngBootstrap - Resizable and Draggable Modal Feature

Currently, I am attempting to integrate Bootstrap version 4 with Angular 8. My main goal is to create a modal that is both re-sizable and draggable. Although there are some examples available for other versions such as 3.xx, none seem to be specifically de ...

Utilizing HTTP request headers in Angular 6

Recently starting out with Angular, I've been working with the latest version. My current challenge involves executing a post request but I keep encountering a CORS issue. I suspect that the problem lies in the absence of a content type in my request ...

How does using ngFor and ngModel in Angular cause a change in one select to affect others?

I am looking to implement a feature where users can create multiple select dropdowns, choose options for each one, and then aggregate these selections into an array that will be sent to a parent component. My current approach involves using an *ngFor loop ...

What is the best way to upgrade Angular from version 10 to 12?

Currently tackling an Angular project migration from version 10 to version 12. Unfortunately, the project seems to be encountering issues post-migration and is not running as expected. ...

Typescript is being lenient with incorrect use of generics, contrary to my expectations of error being thrown

Encountered a puzzling Typescript behavior that has left me confused. Take a look at the following code snippet: interface ComponentProps<T> { oldObject: T } function Component<T>({ oldObject }: ComponentProps<T>) { const newObject = ...

I am seeking a way to access the child infoWindow within a Google Maps marker in Angular 5

I am working on an Angular 5 application that utilizes the Angular Google Maps(AGM) library available at . I have implemented functionality where clicking on an item in a list within one component triggers the display of a child infoWindow associated with ...

Incorporating marker tags to different sections of text within a contenteditable div

The main objective of this feature is to enable users to select placeholders within message templates (variable names enclosed in %). Inspired by Dribbble The API provides strings in the following format: "Hello %First_Name% %Middle_Name% %Last_Name% ...

Angular - Showcasing Nested Objects in JSON

I am experimenting with using angular ngFor to iterate through this data: Link: Although I can successfully retrieve the data by subscribing to it, I encounter an issue when trying to display attributes that contain objects. The output shows as [object O ...