Using Angular2 to assign the response from an http.get request to a class object

I am a beginner in Angular and I have a JSON file that holds the configuration URL for my application.

Path: app/config/development.json

{
   "apiUrl": "http://staging.domain.com:9000/",
   "debugging": true
}

Below is the content of my config.service.ts file:

export class ConfigService {
    private apiURL:any;
    constructor (private http: Http) {}

   getApiURL(){
       this.http.get("app/config/development.json").map(res:Response=>res.json())
      .subscribe(data=>{
         this.apiURL = data;

       })

        console.log(this.apiURL);//this returns undefined
   }

}

I am trying to ensure that this.apiURL captures the response from the http.get method. However, even when I create another method, the value of this.apiURL remains unchanged from the getAPIURL() method.

someMethod()
{
   console.log(this.apiURL)//this must contain the response from http.get
}

Answer №1

If you want to implement this functionality, here is an example of how it can be done within your service file.

// Define the model you are working with
getApiURL():Observable<Object[]>{     
  return this.http.get(this.whateverURL)
            .map(res:Response=>res.json())
            .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}

Next, in your component file:

yourData:Object[];
// Define the Model you are using.
// Assuming yourService is the instance of your service which was set up in the constructor.
this.yourService.getApiURL()
      .subscribe(
          yourData=>{
            this.yourData=yourData;               
          },err=>{
            console.log(err);
            alert("Something went wrong");
          }
      )
}

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

Tips for effectively utilizing JavaScript regex to precisely match a string before triggering the submit button

I have a form in Angular with a text input field that requires the entry of lowercase letters separated by commas, like this: c, d, e, g, a, f etc... Currently, the submit button activates as soon as any part of the input matches the required format, allo ...

What is the process for saving information to a database with JavaScript?

I am currently utilizing the Google Maps API for address translation, primarily through the use of a geocoder. I am interested in saving these results to a local database for future reference, as there are limitations on the total number and frequency of ...

Issues arise when using PHP4 in conjunction with Ajax, the json_encode function, and

I have been tasked with a project for my company that requires PHP4 development. The goal is to display a list of mobile phone brands and their prices, as well as the ability to filter them using multiple checkboxes. However, I am facing an issue where the ...

Revamping HTML with AngularJS Directive: Enhancing the Layout with New Angular Attributes

I am currently facing an issue with the compiler not recognizing a new attribute I have added in a directive. In my Angular TypeScript code, I have the following setup: public class MyDirectiveScope: ng.IScope { foo: boolean; } public class MyDirecti ...

Filtering observables to handle routing in Angular Material Autocomplete is a must-have skill to master

I am currently working with Angular Material version "^6.4.7" and Angular version "^6.1.9". I have set up routing to navigate through a menu filled with observables, using the id of these observables for navigation. Now, I need to implement an autocomplete ...

Dealing with multiple POST requests at once in Node Express JS - Best Practices

I've been working on a Node project with Express to handle incoming GET/POST requests. I have set up routes to manage various types of requests. One specific route, /api/twitter/search, calls a function that uses promises to retrieve Twitter feeds and ...

Is it possible to show one element while hiding others upon clicking using JavaScript?

Concept My idea is to create a website with a navigation menu where only one section is visible at a time. Each section would become visible upon clicking a specific button in the navigation bar. Challenge I attempted to achieve this using the following ...

I noticed that when I include the www in the URL, I am unable to retrieve the API results. However, when I exclude the

Whenever I try to access my website through www.mywebsite.in, it fails to display my data. However, if I visit the site without the www prefix, everything works fine and I can retrieve data from the database. I'm currently utilizing APIs for both get ...

After removing an element from an array in Vue.js, how can we adjust its class to reflect the change?

Apologies for my lack of proficiency in English. I am eager to find a solution to resolve these issues. I am working on a todolist and encountering an issue where the class ('centerLine') continues to affect the next element after deleting an a ...

Rendering an Angular page with data using Node.js

I have a scenario for my website where users need to input a URL with a parameter (an ID) and receive back the corresponding page containing information from the database. I am using Angular4 but I am unsure of how to achieve this. It's straightforwa ...

choose a value from a dropdown menu to reset other dropdowns to their default values

I am encountering an issue with my PHP form that consists of 7 dropdown lists. Whenever I select a value from one of the dropdown lists, I want the other 6 to reset to their default values if they were previously opened. I believe using JavaScript is neces ...

Searching for a solution on how to retrieve data server-side in the newest version of Next.js? Attempted to use getStaticProps but encountering issues with it not executing

Currently tackling a project involving Django Rest Framework with Next.js, and encountering a roadblock while trying to fetch data from the API. Data is present at the following URL: http://127.0.0.1:8000/api/campaigns, visible when accessed directly. The ...

Is there a way to categorize data and sort it by using an action and reducer in redux?

I have developed a filtering system that allows users to filter data by different categories such as restaurants, bars, cafes, etc. Users can select whether a specific category should be displayed or not, and this information is then sent to the action and ...

Loading Ajax content into div (Wordpress) without pre-loading the font can cause display issues

Currently, I'm implementing a JavaScript function within Wordpress using Ajax to load the content of a post into a modal div when specific elements are clicked. Here is an example of how the JS function appears: function openProjectModal($that) { ...

"Utilizing react.js allows for the direct access of DOM elements by the main parent component

Is there a way to trigger click events on deeply nested DOM elements within my component hierarchy without passing down callback functions to each individual component? I'm looking to execute these events from the top parent App component using EventT ...

Does angular have a feature comparable to JavaScript's .querySelectorAll()?

I developed an inventory calculator in JavaScript that provides item count based on weight. The calculator has 4 inputs, and now I'm looking to replicate the same functionality using Angular. Is there a method in Angular similar to .querySelectorAll() ...

Refresh information periodically within a Node.js application

Recently, I developed a web application using nodejs to fetch data from Amazon. My goal is to have the app update at regular intervals for different purposes: - Every 15 minutes for real-time inventory monitoring - Once daily for less frequently changing d ...

Making Node.js Wait Until a Function Completes its Execution

Currently, I am using a for-loop in Node.js to run the x() function from the xray package. This function scrapes data from webpages and then writes that data to files. The program works well when scraping around 100 pages, but I need it to handle around 10 ...

Tips for displaying a page within a parent div upon clicking a button in a child div

Hey there, I'm new to scripting and I've run into a problem. I'm trying to figure out how to load a page in a parent div when clicking buttons in a child div. Specifically, I want to load a specific page in the parent div. Just to clarify, t ...

Attempting to highlight a specific list item by using the CSS current class to emphasize its active state

I've been experimenting with different solutions I found in previous questions, but unfortunately, none of them have worked for me. I suspect the issue lies in the fact that the element is deeply nested within CSS classes, and my lack of experience is ...