Converting an HTTP request and incorporating a success function in Typescript and Angular2

I am working on a http request:

private getValues() {
  this._watchlistElements.map(v =>
    this.http.get('http://localhost/getValue/' + v.xid)
      .subscribe(res => {
        this._values.push(res.json());
    }));
};

When the request is successful, I want to simplify it into one line of code:

this.vars.map((v,i) => v.push(this._values[i].value));

My query is how can I achieve something similar to .success: function(){} in normal ajax with my current code?

Any assistance will be appreciated.

UPDATE

private getValues() {
  this._watchlistElements.map(v =>
    this.http.get('http://localhost/getValue/' + v.xid)
      .subscribe(res => {
        this._values.push(res.json());
      })).then(console.log());
};

When attempting to use the then method in Angular2, an error occurs. Can anyone advise me on which component I need to import for it to work properly?

Answer №1

Utilizing observables, the http function is capable of performing actions in the following manner:

 private fetchValues() {
      this._watchlistElements.map(value =>
        this.http.get('http://localhost/getValue/' + value.xid).map(response=>response.json())
          .subscribe(response => {
           //success
          },
         error=>{
             //error handling
          });
      }

In case you prefer promises exclusively,

private fetchValues() {
  this._watchlistElements.map(value =>
    this.http.get('http://localhost/getValue/' + value.xid)
      .toPromise()
      .then(response=>{response.json()}).catch(handleError);
};

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

Ways to determine if a dynamically generated script tag has been successfully executed

Recently, I've been experimenting with dynamically creating a script tag: var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.charse ...

Utilizing the Map Function for Monitoring Multiple Items

I need to loop through an array of objects to determine if specific criteria are met. Let's consider the structure of my array: const arrayOfItems = [ { delivery_method: { delivery_method: 'car', delivery_rate: 1, pi ...

Keeping an HTML field constantly refreshed with dynamic content from Django

Imagine having two input fields along with an HTML paragraph displaying a Django value. Field A: <input ...> Field B: <input ...> <p>{{ sum }}</p> The goal is to have the sum update in real time, meaning that once both numbers ...

Utilizing the adapter design pattern in Angular with TypeScript for enhancing a reactive form implementation

I've been struggling to understand how to implement the adapter pattern in Angular6. Despite reading numerous articles and tutorials, I still can't quite grasp the concept. Could someone provide some insights on this topic? Essentially, I have a ...

Overlapping Divs - HTML Elements Crossing Paths

My challenge is to position the Social Icons at the bottom of the screen and align the Image Gallery in the middle. However, the social Icons keep moving to the center of the screen and the Image gallery ends up overlapping them, making it difficult for me ...

What is the best way to pass a variable to the chrome.tab.create function?

Is there a way to pass a variable to the `chrome.tabs.create` function? I am currently working on setting up event listeners for my anchors, but I am faced with a challenge as I am creating them within a for loop: for (var i = 0; i < links.length; i++) ...

AngularJs monitoring changes in service

Why does changing the message in the service not affect the displayed message in 1, 2, 3 cases? var app = angular.module('app', []); app.factory('Message', function() { return {message: "why is this message not changing"}; }); app ...

What is the best way to include a div element with a dynamic animation on a webpage?

I'm attempting to create a laser beam that can shoot enemies on the screen, much like in classic games such as Space Invaders or Galaga. However, I am encountering difficulties getting the laser to move when I click the button. Below is the code I hav ...

React.JS Tip: Automatically Make Alerts Disappear in 2 Seconds!

How can I make my alert automatically disappear after 2 seconds in React.JS? Currently, the alert only disappears when I manually close it using the fecharAlerta props function. import { useEffect } from "react" import { useState } from "r ...

Error in VueJS/Typescript: Module 'my-module' or its type declarations are not found

Hey fellow developers! I'm currently working on a Vue2 setup with Nuxt and Typescript. I'm facing an issue while trying to install the awesome vue-slick-carousel module via yarn. When attempting to import the module in my component, Typescript th ...

Creating a customized TextField look with styled-components and Material-UI's withStyles feature

Take a look at this customized TextField style with Material-UI's withStyles: export const StyledTextField = withStyles({ root: { background: 'white', '& label.Mui-focused': { color: 'white' }, ...

How can the printing of content be adjusted when the browser zoom function is activated?

Is there a way to prevent the content from zooming when printing while the browser is zoomed in? The goal is for the printing (using iframe) to remain unchanged even if the browser is zoomed. I attempted: document.body.style.transformOrigin = 'top le ...

Enhancing AngularJS view rendering using ngshow

Currently, I am working on a view where ng-show is used to display a select DOM object when certain conditions are met, and an input DOM for all other scenarios. However, I have noticed that there is a significant delay in the disappearance of the input bo ...

What could be the reason for my function not being executed in this particular scenario with my calculator HTML code?

Memory = "0"; Current = "0"; Operation = 0; MAXLENGTH = 30; alert("yea"); function AddDigit(digit) { alert("yea"); if (Current.length > MAXLENGTH) { Current = "Aargh! Too long"; } else { if (eval(Current) == 0) { Current = dig; ...

What is the process by which React loads and runs JSX content?

What is the method used to identify and handle JSX code? <script src="src/main.js" type="text/babel"></script> ...

Best type for an array of dictionaries

Is there a way to correctly assign the variable r without utilizing any? const d = [{ result: 'aEzRuMA6AtQ6KAql8W9V' }, { result: 'N6mkKsnFJj98MHtYMxIi' }] const result = d.map((r: HERE) => r.result) console.log(result ) // will pr ...

Is there a way to verify DNSSEC compatibility using node.js code?

Struggling with incorporating DNSSEC compliance checks into my web analytics tools using NodeJS. The standard library's dns module does not seem to accept DNSSEC record types such as rrsig, ds, nsec, and nsec3. Despite checking the documentation, thes ...

Using the <Field> component in Vee-validate ensures that your form will always be valid when submitted

Hello all, I am currently working on a Vue 3 project and utilizing vee-validate v4 for form validation. My forms are structured as follows <template> <div> <VForm v-slot="{ meta }" ref="form" > ...

avoid saving views in Angular.js

It appears that all of my HTML content is being completely cached in Chrome for some unknown reason. Currently, I am using Angular 1.2 with a .NET Web API 2 project, and the content is being served in index.html. Although I have not made any changes to t ...

Uploading files using Ajax

Currently, I am attempting to utilize ajax for submitting a form that includes a file input. There are specific requirements that must be met in order for this process to work as intended. The file input should only be activated when a designated button ...