What steps should I take to retrieve my information from a typescript callback function?

While I am familiar with using callbacks in JavaScript, I have recently started learning Angular and TypeScript. I am facing an issue with getting my data from a service back to where I need it after executing the callback function. The callback itself is functioning correctly as indicated by the console log statements being output in the correct order. However, I am struggling with the proper format to retrieve and handle this data. Despite searching for a solution online, I have not been able to find the right combination of code. I am currently sending my data back using `CallBack(data)`, but I am uncertain about how to receive it.

//Output
running
Got some data etc
Finished


// In Component
  constructor(private imageService: ImageService) {
    console.log('running');
    this.imageService.test(()=>{
      console.log('Finished');
    });
  }
  

// In a service
  test(CallBack: { (callback: any): void; (): void; }) {
     this.httpClient.post('http://localhost/api/gallery/buildGallery', this.postData)
   .subscribe((data)=>{
       console.log('Got some data',data);
       CallBack(data);
     },(error)=>{
       console.log('error');
      CallBack ();
     });
  }

Answer №1

Let's attempt it this way :

Component :

constructor(private imageService: ImageService) {
  console.log('running');
  this.imageService.test(...).subscribe(res => {
    console.log(res);
  });
}

Service :

test(postData: any): Observable<any> {
  return this.httpClient.post('http://localhost/api/gallery/buildGallery', postData);
}

Here are a few illustrations of How to manage errors on subscribe. It should resemble :

this.imageService.test(...).subscribe(
  res => {
    console.log('Success : ', res);
  },
  error => {
    console.error('Error :', 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

"Upon the initial page load, the persistence of values in local storage using Next.js, React, and Recoil

Check out this code I have, const Layout: React.FC<LayoutProps> = ({ children }) => { const darkMode = useRecoilValue(darkModeAtom) console.log('darkMode: ', darkMode) return ( <div className={`max-w-6xl mx-au ...

What causes the "node: bad option" error to occur when I include a custom flag in the nodejs command line within an Angular 9 application?

Seeking assistance with adding a custom flag to the npm start command in an Angular 9 project. The goal is to intercept proxy requests within the local server and manipulate data. However, encountering the "node: bad option" error consistently. Looking for ...

Differences in file sizes in Angular-CLI builds

After building my Angular app, I noticed the following output: https://i.sstatic.net/ZRtxU.png Upon closer inspection, it is evident that 0.7f787ebcd865a23bb4ea.chunk.js and vendor.fbdfd024192bddab02d3.bundle.js are quite large. To confirm their sizes, ...

What is the best way to establish communication with the root component in Angular?

I have implemented a modal in the root component that can be triggered from anywhere. However, I am facing a dilemma on how the bottom component can communicate with the top component without excessive use of callback functions. Root Component <contai ...

Exploring an array of objects to find a specific string similar to the one being

I recently developed a TypeScript code snippet that searches for objects in a list by their name and surname, not strictly equal: list = list.filter( x => (x.surname + ' ' + x.name) .trim() .toLowerCase() .sear ...

Addressing the issue of potential null objects within an Angular FormGroup

While working on my Angular-15 project, I encountered an issue with the code in the component.ts file: component.ts: export class CountryCreateComponent { countriesData: any[] = []; selectedCountryCode: string = ''; selectedCountr ...

Incorporate JavaScript Library into StencilJs Using TypeScript

Recently, I decided to incorporate a JavaScript library called Particles.js into my project. The process involved importing it and initializing it within my component: import { Component, h } from '@stencil/core'; import * as particlesJS from &a ...

Angular 4 - Resolve ngModelChange Error: Property '...'is Undefined When Binding Two Select Form

I need assistance with implementing a functionality in Angular 4. I have a JSON model that contains information about books, including their titles and authors. I want to create two select form elements (dropdowns): the first dropdown should display the ti ...

Trouble accessing the Ionic SQLite database: Unable to open

I encountered some errors while attempting to connect my ionic app to a database. I am currently running the app on an android device using Google Chrome DevTools to troubleshoot the issue. Check out the createDatabase() function and the specific error th ...

The function cloneElement does not share any properties with the type Partial<P> and Attributes

I'm encountering a perplexing issue with my code. When I attempt to call cloneElement with the second parameter being of type Type { foo: number } has no properties in common with type 'Partial<Child> & Attributes', TypeScript thro ...

Ways to address memory leakage issues in Angular

Is there a way to manually optimize the Garbage Collector by forcefully pushing variables into it? For example, if we have a root or global level variable in an Angular component that is no longer needed when switching to another page, how can we ensure it ...

Change the type of an object to a different type

Within my class, I have set the type of range to IntervalRange. export class Test {range: IntervalRange;} Then, in the parent class, I initialize the value: export class TestInitializer { Create(){ return <Test>{ range: IntervalRange.i ...

What causes the failure of Angular 2 RC.6 routing when bundled with ngc + Rollup?

I have been exploring the new AOT Compiling feature in RC.6, but I have encountered a stumbling block. While I can successfully create a bundle using ngc => Rollup => Babel, I keep getting multiple warnings every time I run Rollup: The 'this&ap ...

Angular: leveraging the power of *ngFor and *ngIf while incorporating index values in nested components

I want to display various items from an array observable within grid-card components. I also aim to restrict the number of grid cards displayed based on specific variables in my component, such as gridCols*maxRows, by utilizing a conditional check with *ng ...

When using Angular, automatically shift focus to the next input field by pressing the

I am faced with a challenge involving multiple editable inputs on my screen. Alongside these editable inputs, there are buttons and disabled inputs present. The current behavior is such that when I press Tab, the focus shifts to the HTML elements between ...

What is the best way to selectively pass certain values to the args object?

Is there a way in TypeScript to pass only one argument into args and have other values be default without using "args = {}" or declaring defaults within the function to avoid issues with intellisense? function generateBrickPattern ( wallWidth: number, ...

Customizing the output format of Ng Date Picker beyond the standard ISO-8601

Just to clarify, I'm talking about a specific DatePicker component that can be found at the following link: Although the DatePicker interface is user-friendly and visually appealing, I'm facing an issue with the way it outputs values. While ther ...

What is the best way to inform Angular2 RC1 about updates in the DOM?

Originally inspired by a discussion on Stack Overflow, this scenario presents a simpler use case. The issue at hand is how to inform Angular2 about externally added DOM elements that contain Angular directives. For example, adding a new button with a click ...

Why did the compilation of Next.js using TypeScript and ESLint succeed despite encountering errors?

I've been delving into Next.js and encountered unexpected results when integrating TypeScript and ESLint. ESLint seems to work well with TypeScript, but my project compilation is successful despite encountering errors. It's puzzling why the comp ...

The 'isLoading' property is not found in the type 'UseMutationResult<AxiosResponse<any, any>, Error, void, unknown>'.ts(2339)

I'm currently working on implementing a delete functionality that displays a loading state using the useMutate function from tanstackquery. However, I encountered an issue where the loading state is not shown when I click the delete button, even after ...