Getting observable subscriptions results in undefined

One of the services in my application utilizes a dictionary to store HTTP responses, mapping an ID to a specific URL.

import { HttpClient} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class urlService {
  private map: Map<string, string>;

  constructor(private http: HttpClient) {
    this.map = new Map<string, string>();
  }

  public getUrl(id: string): Observable<string> {
    if (this.map.has(id)) {
      return of(this.map.get(id));
    }

    this.http.get<any>(`...sampleURL...`)
    .subscribe((result) => {
      this.map.set(id, result.url);
      return of(this.map.get(id));
    });
  }
}

However, despite my efforts, when I attempt to retrieve this URL from my app component, the result is consistently undefined.

this.urlService.getUrl(this.id).subscribe(
  url => console.log(url)
);

It seems that the problem lies in the subscription returning an Observable within urlService.getUrl(). Can anyone provide some guidance on how to address this issue?

I did attempt to use switchMap as a solution, but unfortunately, it did not resolve the problem.

this.http.get<any>(`...sampleUrl...`).pipe(
  switchMap(result => {
    this.map.set(id, result.url);
    return of(this.map.get(id));
  }))
.subscribe();

Answer №1

Your current implementation of the getUrl method is not returning the Observable correctly. It is currently not providing any return value, resulting in undefined being returned.

To correct this, you should return the Observable using the map operator from rxjs.

import { map } from 'rxjs';

public getUrl(id: string): Observable<string> {
  if (this.map.has(id)) {
    return of(this.map.get(id));
  }

  return this.http.get<any>(`...sampleURL...`)
      .pipe(
        map((result) => {
          this.map.set(id, result.url);

          return this.map.get(id); 
          // Or 
          // return result.url; 
        })
      );
}

Check out the demo on StackBlitz

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

When attempting to navigate to a sub-route, I am encountering the error message: "Unable to find a matching route" in Angular 6

The initial code is functional, but not the best practice. const FooProcessingRoutes: Routes = [{ path: '', pathMatch: 'full', redirectTo: '/foo-processing/list', }, { path: 'list', component: FooListCompo ...

Encountering the Selenium Webdriver HTTP error within an Angular 4 project

ERROR Detected Issue found in: ./node_modules/selenium-webdriver/http/index.js Module not found: Error: Unable to locate 'http' in 'C:\Users\aprajita.singh\Documents\Angular 4\Auto-Trender-Project\node_modules ...

How to Extract the Specific Parameter Type from a Function in Typescript

After generating a client for an API using typescript-node, I encountered the following code: export declare class Api { getUser(username: string, email: string, idType: '1298' | '2309' | '7801') } I need to access the ...

Is it possible to verify or authenticate the properties received directly from the associated type or interface?

Looking for a more efficient way to handle validation in my component that takes an array of tabs and children as props. I would like to check if the children provided are the same length as the tabs array directly from the type declaration or any cleaner ...

best practices for running callbacks in sequence within Angular

Seeking a solution to ensure Angular waits for data fetching to complete before proceeding with execution in ngOnInit: fetchData() { console.log('2') this.http.get("http://jsonplaceholder.typicode.com/users").subscribe( (data) =&g ...

Is it necessary to create a wrapper for Angular Material2 components?

I have multiple angular 5 projects in progress and my team is considering incorporating material design components from https://material.angular.io/. Would it be beneficial to create a wrapper layer to contain the material design components? This would me ...

Why am I encountering an issue while trying to access req.user.id?

Having set up passport authentication on my express, node project, I encountered an error when trying to access req.user. The error message displayed is Property 'id' does not exist on type 'User'.ts(2339). Below is the relevant code sn ...

Error: The function type 'Dispatch<SetStateAction<string>>' cannot be assigned to the type '(value: OptionValue) => void'

I recently dove into the world of integrating Typescript generics with React after reading this insightful article. I followed the code provided in the article, but encountered the following error: Type 'Dispatch<SetStateAction<string>>&ap ...

Adding an icon to the contents of a specific column in Angular material

Struggling to figure out how to incorporate an icon into the data in the Status column using Angular material. Here is the markup of my page: <table mat-table [dataSource]="dataSource"> <ng-container *ngFor="let ...

Activate router link on a pair of routes

When using Angular, how can I ensure that the routerlink stays active on multiple routes? <li routerLinkActive="active"><a routerLink="dashboard">Dashboard</a></li> Currently, the style active is applied when the route is set to " ...

What strategies can I implement in Angular to enhance the efficiency of my code and reduce load time? Presently, the load time stands at 2

I'm looking to enhance the performance of my code to increase speed. How can I optimize the following code snippet to further improve load time? Additionally, any suggestions on what considerations I should keep in mind would be greatly appreciated. C ...

Save information on the server and organize it into an array for use in local operations

Currently, I am working on the ShoppingApp using Angular for the front-end and Firebase for the backend. I have defined a model for the category as follows: import { ProductModel } from "./product.model"; export class CategoryModel { public id: number; ...

What is the best way to set up initial state in react-native-day-picker?

I have been experimenting with implementing react-native-calendar into my project. Here is the code snippet I am working on: import React from 'react'; import {Calendar} from 'react-native-day-picker'; const MyCalendar = () => { ...

Revealing a single element in an Angular 6 application that is utilized by several modules

As I am in the process of breaking down a large module into smaller ones, I have encountered an issue that needs to be addressed. Here are the specifics: The Search component is currently being used across multiple components. Initially, it was declared i ...

Issue with obtaining access token in Angular 8 authentication flow with Code Flow

As I work on implementing SSO login in my code, I encounter a recurring issue. Within my app.module.ts, there is an auth.service provided inside an app initializer. Upon hitting the necessary service and capturing the code from the URL, I proceed to send a ...

Angular's capability for manipulating data asynchronously

I am relatively new to this, and I am facing difficulties in handling data manipulation in the frontend of an app that I'm currently developing. In my code, there are two functions named "getTipoEtapas()" and "getEtapasporTransfo" which utilize two s ...

What is the process for importing WebAssembly functions into TypeScript?

I currently have a TypeScript project and am in the process of incorporating a WebAssembly Module to replace certain functionalities. Successfully importing the WebAssembly module involved moving the .wasm loading logic to its own .js file, which is then ...

Encountering the error message "Subscribe is not a function in Jasmine" while

Encountering an issue where I am receiving an error stating "subscribe is not a function" in Angular unit testing. Here is the call that I have implemented in my component: this.myService.employees.subscribe(emp => this.emp = emp); Despite creating a ...

Can I modify the cookie domain for NestJS SessionModule on a per-request basis?

I am currently using NestJS with SessionModule to handle user cookies successfully. However, I have a requirement to override the domain name for certain requests. I am uncertain about how to achieve this within NestJS, as the domain setting appears to b ...

Developing a Library for Managing APIs in TypeScript

I'm currently struggling to figure out how to code this API wrapper library. I want to create a wrapper API library for a client that allows them to easily instantiate the lib with a basePath and access namespaced objects/classes with methods that cal ...