"Sequencing http.get requests in Angular 2 using

In my service, I have a series of http.get requests structured as follows:

constructor(private http:Http) {}

getDetails(sysID:string){

var details;
this.http.get('https://blahURL').map(res => res.json().filter(f => f.id == another.id)[0]).subscribe(
    (data) => details = data,             // Executed if res.status >= 200 && <= 299
    (err) => console.log(err),            // Executed if request fails
    function(){                           // On completion

      console.log(this);

      this.http.get(...) //<- fails

Although the "on Completion" function is triggered, the this object logged in the console appears to be a SafeSubscriber instance, causing the subsequent http call using this.http to fail.

What could be the issue here?

Answer №1

Utilize the arrow symbol to maintain the reference of this.

Exchange

function(){  // Upon finishing

  console.log(this);

  this.http.get(...) //<- fails

With

()=>{ // Upon completion

  console.log(this);

  this.http.get(...) 

Answer №2

When you are inside the subscription function, the second instance of this no longer points to your original object.

To fix this issue, try creating a reference to it before making the initial http call. For example:

let self = this;

You can then use this reference self inside your subscription callback or error function like this:

self.http.get(..)

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

Seeking assistance with producing results

Is there someone who can provide an answer? What will be the output of the code snippet below when logged to the console and why? (function(){ var a = b = 3; })(); console.log("Is 'a' defined? " + (typeof a !== 'u ...

Book of Tales displaying Emotion Styling upon initial load only

I'm currently working with the styled api provided by emotion in order to create a custom styled button. const StyledButton = styled(Button)` background-color: ${theme.palette.grey['800']}; width: 50; height: 50; &:hover { ba ...

Executing asynchronous function in Angular using Typescript

My team and I are new to Angular and we are facing a challenge with invoking methods in sequence and returning a value. The issue is that the return statement is being executed before the completion of the execution process. We have tried various approac ...

Encountering the error "TS(2604): JSX element type 'App' does not have any construct or call signatures" while trying to export an array of JSX Elements

I have a function that returns an array of JSX Elements. When I pass this to ReactDOM.render, I encounter the error mentioned above. wrappers.tsx const FooterWithStore:React.FC = () => ( <Provider store={store}> <FooterLangWrapper ...

Issue with loading React Router custom props array but custom string works fine

I am facing an issue with my ReactTS-App where I pass a prop via Router-Dom-Props to another component. The problem arises when I try to use meal.food along with meal.name, or just meal.food alone - it doesn't work as expected. Uncaught TypeError: mea ...

What steps should be taken to guarantee that the view is created only after receiving values from the route params subscription?

How can I ensure that the View is only rendered after the subscription has received values? When clicking on the Edit button in MyComponent_1, Angular navigates to MyComponent_2. In MyComponent_2, the view contains a form whose values are dependent on rout ...

It seems that an error has occurred: DOMException was thrown because the attempt to run 'importScripts' on 'WorkerGlobalScope' has failed. The script located at 'http://localhost:4200/BlinkCardWasmSDK.js' was unable to load properly

Recently, I attempted to integrate this credit card reader into my Angular application. Despite carefully following all the installation steps and obtaining a valid license key, I encountered the following error: Error during the initialization of the SDK! ...

Utilizing a powerful combination of Angular 5, PrimeNG charts, Spring Boot, and JHipster

I am facing an issue with creating charts using PrimeNG. The main challenge I'm encountering is the conversion of data from a REST API in Angular 5 (TypeScript) and retrieving the list of measurements from the API. I have an endpoint that returns my m ...

Tips for manually inputting dates in Primeng Calendar Datepicker with the slash "/" symbol

I need assistance with adding slashes to manual input when using the primeng Calendar component. <p-calendar [monthNavigator]="true" [yearNavigator]="true" yearRange="1950:2021" ngModel [required]="tru ...

An error has occurred: Type 'x' is not compatible with type 'x' (during Vercel deployment)

I encountered an issue during Vercel deployment which displays the following error message: - Type error: Type ' ({ params }: DashboardPageProps) = Promise' is not compatible with type 'FC<.DashboardPageProps>' Type 'Promise ...

Tips on ensuring a <video> element occupies the full height and width of the screen

I am currently working on an Angular 6 project where I am live streaming a user's webcam to an HTML element. My goal is to simulate the experience of capturing a video or photo on a mobile device. However, the size of the video is currently small. I ...

Issues with loading Kendo ScrollView dynamically within an Angular ng-template

In an effort to add dynamism to this sample, I am working on pulling items[] from a database. You can view the progress on this link. To achieve this, I have initiated a service call to load the items: public isFormReady: boolean = false; public items: ...

Arranging an array of objects in typescript with elements implicitly having an undefined type

Currently, I am facing a challenge where I need to sort an array of objects within a function. The catch is that the function receives the key as a parameter, making it unknown: export interface ProductsList { id: boolean nome: string qtde: number ...

Video player for Angular 2

Hey there! I am currently exploring Angular 2 and attempting to create a video playlist feature. My goal is to showcase my favorite videos in a table layout, where clicking on a row will lead to the playback of the selected video. Right now, I am passing t ...

Is there a way in Angular Material to consistently display both the step values and a personalized description for each step?

Is there a way to display both numerical step values and corresponding custom text in Angular Material? I prefer having the number at the top and the descriptive text at the bottom. Check out this image for reference: https://i.stack.imgur.com/LGMIO.png ...

Leveraging File functionality in TypeScript

In the process of developing a web application with Angular 4 and Typescript, I encountered an issue while attempting to retrieve the date of a file for upload. Specifically, when trying to access the lastModified property of a File object, Typescript retu ...

Is it recommended for TypeScript to automatically resolve the index.ts file as the default module file?

Struggling with getting the module resolution to work in TypeScript. Consider the following file structure: /modulename/index.ts Should it be resolved like this? import * as modulename from "modulename" I can't seem to make it work. However, imp ...

Check the status of a different website's online presence using JavaScript

Hey there! I'm working with Angular and iframes, and I want to determine whether the target website is online before loading it into the iframe. Here's the code I am currently using: try { await this._httpClient.get(url, { observe: 'respo ...

Throttle the RxJs interval based on the inner observables

Sorry if the way I am asking this question is not clear, I am having difficulty finding the right words to explain it. I am currently working on Selenium automation and here is how the process goes:- Go to a specific page Every 1 second, check if the pag ...

Import reactjs modules without the need for Browserify, Webpack, or Babel

I am attempting to set up a TypeScript HTML application in Visual Studio. My goal is to incorporate reactjs v0.14.7 without relying on tools like Browserify. But, how can I utilize the react-dom module in this scenario? Let's set aside TypeScript fo ...