How to retrieve a variable or map from an HTTP request in Angular 2+?

In my service, I have the functionality to either store an object for access in other components or request data from a web API and return it in a map.

Example of retrieving data from objectService:

get(): any {
    if (this.object == undefined || this.object == null) {
        return this.http.get(this.baseUrl + "/companies/get)
            .map((data: any) => {
                this.object = data;
                return this.object;
            });
    } else {
        return this.object;
    }
}

Using the service to set page title:

ngOnInit() {
    this.objectService.get().subscribe((data: any) => {
        this.title.setTitle(data.name);
    });
}

While this setup works initially when loading the page, navigating to it without a reload throws the error ...subscribe is not a function. This makes sense because I am returning an object instead of an HTTP request.

Therefore, I attempted to modify the get method to simply return the object without making an HTTP request.

Updated get method in objectService:

get(): any {
    if (this.object == undefined || this.object == null) {
        return this.http.get(this.baseUrl + "/companies/get)
            .map((data: any) => {
                this.object = data;
            });
    }
    return this.object;
}

Using the service to set page title with updated method:

ngOnInit() {
    this.title.setTitle(this.objectService.get().name);
}

Now, the issue has shifted where a page refresh results in an error stating that this.objectService.get().name is undefined. However, when navigating to the component without a page refresh, it functions correctly.

If you have any suggestions on resolving this issue, please share your insights. Thank you in advance!

Answer №1

It seems that you are getting confused between observable and normal objects!

My suggestion would be to stick with the initial approach, but when returning the object, convert it to an observable so that it functions properly in your onNgInit

Your service should look like this:

get(): Observable<any> {
    if (this.object == undefined || this.object == null) {
        return this.http.get(this.baseUrl + "/companies/get)
            .map((data: any) => {
                this.object = data;
                return this.object;
            });
    } else {
        return Observable.of(this.object);
    }
}

By doing this, your code will still function normally and work for all scenarios.

ngOnInit() {
    this.objectService.get().subscribe(
      (data: any) => {  // handling response data
        this.title.setTitle(data.name);
      },
      (error: any) => {  // handling errors
        console.log('error: %o', error);
      },
   );
}

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

What coding techniques can be used to create dynamic animation of a log stream in javascript/css

When I have a series of events in my browser, I want to display them as a list with a smooth animation effect. As each new event comes in, I'd like the existing items to slide down gracefully, making room for the new event to fade in at the top of the ...

Creating Styles in Material-UI using makeStyles: Tips for Styling by Element Name

I am currently facing a challenge of adding a rule for all <p> tags within the current component. Despite searching through various sources such as material-ui documentation and Stack Overflow, I have been unable to find any information on how to add ...

Is it a beneficial strategy to remove object keys and assign new keys when iterating through thousands of objects in a loop?

Consider the following array as an example: For instance var a =[{name :"Adi", age:23},{name:"aman" ,age : 23},{name : rob,age:52}]; Is it better to delete the keys 'name' or assign them as undefined? Which approach is more efficient? Does us ...

Tips and techniques for implementing push notifications in front-end applications without the need for a page refresh

I am working on a Python program that inserts data into a XAMPP database. I am looking for a way to continuously monitor the database for any changes and automatically send updates to the frontend without relying on click events. Is there a method simila ...

Determining the type relationship between two generic types when using a union

Here is the code snippet defining a React component using react-hook-form: import { type FieldPath, type FieldValues, type FieldPathValue, } from "react-hook-form"; interface FormControlRadioBoxProps< TFieldValues extends FieldValue ...

Exploring the world of tabbed dynamic routing in Angular 2 version 4

Today I encountered a routing issue that requires assistance from all of you. Currently, I have a sidebar with dynamic tree view navigations on the left and 4 tabs on the right. By default, tab1 is selected to display data related to the active link. Lin ...

Leveraging JavaScript or jQuery to code for advanced enterprise-grade wifi networks

After successfully developing a wifi application that supports personal WPA or WPA2 networks with password validation, I am now looking to expand my skills and tackle enterprise level wifi networks. These networks require more complex validations such as u ...

Determine through programming whether an ng-content slot has been filled in Angular

I have developed a dynamic Angular component that utilizes content projection and slots in the following way: <div class="content-wrapper"> <div class="short-wrapper" [style.opacity]="expanded ? 0 : 1"> ...

Upon clicking the collapse button, the collapsed element briefly appears before its height value is reset to empty in the element's style

Check out this code snippet: <!-- Expand buttons --> <div> <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExa ...

Error encountered in NextJS API: "TypeError: res.status is not a function"

Background In my development environment, I am using NextJS v11.1.1-canary.11, React v17.0.2, and Typescript v4.3.5. To set up a basic API endpoint following the guidelines from NextJS Typescript documentation, I created a file named login.tsx in the pag ...

Having trouble getting errors to display on the Input onChange event with Antd

When using Antd, I am having trouble getting errors in the onChange event. Even when there is an error in a field, I cannot see the errors while typing in that particular field. For example; https://stackblitz.com/edit/react-qurm1n?file=demo.tsx Here are ...

Is there a variance in window.innerWidth between Chrome and Firefox?

body, html { position:absolute; width:100%; height:100%; margin: 0; padding: 0; overflow: hidden; } When using window.innerWidth, there is a discrepancy between the values returned by Firefox and Chrome. Firefox return ...

Does Ext js have a monochromatic theme of blue running through everything

While the blue color may give off a nice office ambiance, it's important to have variety in the appearance of different applications. Is it simple to customize the look in ext js? ...

How can I extract an object from an array by using a string key in either Observable or lodash?

How can I retrieve a specific object (show) from Shows based on its id being a string in a given sample? I am transforming the result into an RXJS Observable, so using functionalities from RXJS or lodash would be greatly appreciated. //JSON RETURNED with ...

Extracting data from HTML that dynamically updates with button click

I am working on extracting data from a webpage with a large table that displays 100 entries by default. At the bottom, there is a dropdown menu where you can select to show 200 entries or view all of them. Is there a way for me to automatically set the dr ...

Dealing with errors in Angular using dependency injection

I'm encountering an issue while attempting to inject $ http to the factory. I received the following error in Angular 1.6: Circular dependency found: $rootScope <- $http <- $exceptionHandler <- $rootScope <- $route Here is what I have b ...

Is it possible for a hybrid app using Angular 7/1.x to enable Hot Module Replacement (H

Having trouble implementing HMR on a hybrid Angular application using the downgradeModule strategy. I previously sought help from a similar question on Stack Overflow Can an Angular 5/1.x hybrid app support HMR? but didn't find a satisfactory answer. ...

Creating a freehand drawing feature with mouse movement using bufferGeometry in three.js r144

I have been working with code from a repository called scribble, which uses three.js r87. In trying to update the code to three.js r144, I followed the steps outlined in the Converting THREE.Geometry to THREE.BufferGeometry tutorial. While one function upd ...

Generating HTML content from XML data with the help of JavaScript

Challenge: Attempting to display one question and its four corresponding answers at a time from an XML file. JavaScript code: var xmlDoc, quest, ans, i, n; xmlDoc = loadXMLDoc("questions.xml"); quest = xmlDoc.getElementsByTagName('main'); do ...

Issue with Colorbox plugin preventing ASP.NET button from triggering postback

Currently utilizing the colorbox modal plugin (http://colorpowered.com/colorbox/) I'm facing an issue with a simple form placed in a master page - the submit button is unresponsive and doesn't trigger any action. It seems like several users are ...