Tips for retrieving a value from a function in Angular that contains an Observable subscription

I am working on an Angular class and I need to create a method that can retrieve a value from an observable and assign it to multiple class properties. Below is a snippet of my code:

export class SomeServiceClass implements OnInit {

someProperty1: someObject;
someProperty2: someObject;
somePropertyN: someObject;

ngOnInit() {
     this.someProperty1 = getValueFromObservableGenericMethod("value1")
     this.someProperty2 = getValueFromObservableGenericMethod("value2")
     this.somePropertyN = getValueFromObservableGenericMethod("valueN")

    console.log(someProperty1); // undefined
    console.log(someProperty2); // undefined
    console.log(someProperty3); // undefined
}


getValueFromObservableGenericMethod(someIncomingString: string): someObject {

    let localVar: someObject;

    this.anotherServiceClass.subscribe(
        data => {
            localVar = data;
        },
        () => {
            return localVar;;
            console.log(localVar);
        }
    )

    return localVar;

}
}

After calling the method, all my class properties are showing as undefined. The variable localVar is available in the complete function. Does anyone have any suggestions on how to properly return values from this function call?

Answer №1

After reviewing the example, here are the necessary modifications:

export class SomeServiceClass implements OnInit {

    someProperty1: someObject;
    someProperty2: someObject;
    somePropertyN: someObject;

    ngOnInit() {
        getValueFromObservableGenericMethod("value1").subscribe(result => {
            this.someProperty1 = result;
            console.log(someProperty1); // now it's not undefined            
        }
}


getValueFromObservableGenericMethod(someIncomingString: string): Observable<someObject> 
{

    let localVar: someObject;
    // I replaced subscribe with map
    return this.anotherServiceClass.map(
        data => {
            localVar = data;
        },
        () => {
            return localVar;;
            console.log(localVar);
        }
    )
}
}

To clarify, properties cannot directly hold an Observable value, so you must subscribe to the function that returns the desired value. Feel free to ask if you have any more questions and I will do my best to explain.

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

The young one emerges within the SecurePath component temporarily

Setting up authorization in React has been a priority for me. Ensuring that users cannot access unauthorized pages within the application is crucial. To achieve this, I have created a custom component as shown below. import { ReactNode } from "react&q ...

An error is thrown when attempting to use npm install, stating "integrity checksum failed. The expected sha1 checksum was sha1-6G...=, but the actual checksum was sha512

I have been browsing through various posts on different platforms trying to solve my issue, but unfortunately, I haven't had any luck. Despite having no prior experience with Angular, I was tasked with installing npm and running an unfamiliar Angular ...

Why is it that after running "ng build" with Angular CLI, the project does not function properly?

(Greetings fellow Earthlings, I come in peace from the distant planet Angular2 (formerly known as Flex/Actionscript). Please pardon my ignorance with this question) Am I mistaken to assume that by running the "ng build" command on my project using Angular ...

Issue - The path to the 'fs' module cannot be resolved in ./node_modules/busboy/lib/main.js

After adding a new React component to my NextJS app, I encountered a mysterious error in my local development environment: wait - compiling... error - ./node_modules/busboy/lib/main.js:1:0 Module not found: Can't resolve 'fs' null Interest ...

The data is not being displayed in the table

I am encountering an issue while attempting to populate the table with data received through props by looping over it. Unfortunately, the data is not rendering on the UI :( However, when I manually input data, it does show up. Below is my code: Code for P ...

``Is there a specific location where I can access the Microsoft Azure msal sign-up feature within Angular

My current Angular version is 5.2.0 and I am struggling to find a tutorial on how to incorporate Azure MSAL for new user sign-up using a Microsoft account. If anyone has any resources or examples on how to achieve this integration without having to update ...

The function fromEvent is throwing an error stating that the property does not exist on the type 'Event'

I'm attempting to adjust the position of an element based on the cursor's location. Here is the code I am currently using: this.ngZone.runOutsideAngular(() => { fromEvent(window, 'mousemove').pipe( filter(() => this.hove ...

Issue with AdonisJS Lucid idempotent methods and the updateOrCreateMany() function

Seeking clarification on a 500 error related to a specific attribute in the database while using updateOrCreateMany(), as opposed to no error when using updateOrCreate(). Here is the code snippet for updateOrCreateMany(): const payload = [ { githubI ...

Sorting the table in Angular Material is proving to be a challenge

I'm attempting to organize data within an Angular table by utilizing the MatSortModule. Unfortunately, the sorted table is not functioning correctly. Below is the provided code: main.module.ts import { MatTableModule, MatSortModule } from '@ang ...

Disable multiple buttons at once by clicking on them

What is the best way to disable all buttons in a menu when one of them is clicked? Here is my code: <div class="header-menu"> <button type="button"> <i class="fa fa-search" matTooltip="Filter"& ...

Having issues with using the class selector in SVG.select() method of the svg.js library when working with TypeScript

Exploring the capabilities of the svg.js library with typescript has presented some challenges when it comes to utilizing CSS selectors. My goal is to select an SVG element using the select() method with a class selector. In this interactive example, this ...

Is there a specific type in Typescript that corresponds to "(event: MouseEvent<HTMLButtonElement>) => void"?

It feels like I'm using the same type (event: MouseEvent<HTMLButtonElement>) => void repeatedly in every component that involves a click event (specifically with buttons). Is there a simpler way to handle this kind of common scenario, maybe t ...

Unable to locate the "lint" target for the project selected OR The data path "" must contain the necessary property 'lintFilePatterns'

Upon transitioning my Angular project structure to a monorepo setup as demonstrated in this tutorial, I encountered several configuration issues that required extensive troubleshooting to resolve. The first error message stated: Cannot find "lint" target ...

Guidelines for saving a webpage as a PDF using TypeScript in Angular 8

Here is the code snippet for downloading the page directly: downloadPage(cmpName) { let downloadContents = document.getElementById(cmpName).innerHTML; let originalContents = document.body.innerHTML; document.body.innerHTML = downloadContents; // Add cod ...

Testing the GET method in an Angular service: A guide

I'm currently facing an issue with my service method and unit test setup. Despite writing a unit test for the getter method, the coverage report indicates that this method is not covered. I would appreciate any advice on what might be going wrong in m ...

Tailored validation for targeted field

How can I validate a partial form based on requirements? Built with Angular 7 and Clarity I have a form using the clrForm component that includes: Field 1: Name Field 2: URL Field 3: Date The form also has two buttons: Button 1: Verify Button 2: Su ...

Get the dynamic type as the return value in a TypeScript abstract class method with generic type T

Within my codebase, I have created an abstract class: export abstract class Filters<P> { protected field: string; protected constructor(field: string) { this.field = field; } protected abstract getFilter(): P; } Additionally, there is ...

Intellisense missing in VSCode for Angular and typings

Attempting to start a new project using Angular 1.5.5 and looking to incorporate TypeScript into my coding process within Visual Studio Code. I have included the necessary typings for Angular in my project: typings install angular --save --ambient I&ap ...

What is the best way to utilize derived types in TypeScript?

Given object A: interface A { boolProp: boolean, stringProp: string, numberProp: number, ...other props/methods... } Now, I need objects that contain one of the properties from A and set a default value for it, with other properties being irre ...

Type Error TS2322: Cannot assign type 'Object[]' to type '[Object]'

I'm facing an issue with a code snippet that looks like this: export class TagCloud { tags: [Tag]; locations: [Location]; constructor() { this.tags = new Array<Tag>(); this.locations = new Array<Location>(); ...