Anticipating the completion of the observable callback

I'm facing an issue with the observables in my service setup. Here is how it looks:

return Observable.forkJoin(
   this.http.post(this.baseUrl, JSON.stringify(user), this.serverConfig.getJsonHeader()),
   this.awsService.uploadData(params)
)

In my component, I subscribe to them like this:

.subscribe(
    data => {
       console.log('data[0]',data[0]);
       console.log('data[1]',data[1]);
    }
);

There's also a uploadData function I have implemented:

uploadData(params: any): Observable<any> {
      return Observable.of(
          this.getBucket().upload(params,
               (error, resp) => {
                  console.log('error', error);
                  console.log('resp', resp);
               }
           )
       )
   }

The issue I'm facing is that the callback function within the uploadData method is running after the subscription instead of before. How can I make sure the callbacks run before the subscription? Any suggestions on what I should do?

Answer №1

After some troubleshooting, I managed to resolve the issue. Instead of using an observable, I switched to using a promise in my code like so:

uploadFiles(parameters: any): Promise<any>{
        return new Promise((resolve, reject) => {
            this.getStorage().upload(parameters, (error, result) => {
                if (error)
                    reject(error);
                 else
                    resolve(result);
            });
        });
    }

Furthermore, I made adjustments to my fork join implementation as shown below:

Observable.fromPromise(this.cloudService.uploadFiles(parameters))

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

Having trouble pushing to an array in Angular typescript? It seems to be returning as undefined

As a newcomer to Angular with a basic understanding of JavaScript, I am attempting to create a program that can solve Sudoku puzzles. In a 9x9 grid, there are a total of 81 points or squares. To efficiently check for violations of Sudoku rules - no repeati ...

Tips for extracting a keyword or parameters from a URL

I'm in the process of creating my personal website and I am interested in extracting keywords or parameters from the URL. As an illustration, if I were to search for "Nike" on my website, the URL would transform into http://localhost:3000/searched/Nik ...

Create a Typescript function that has an optional object argument containing optional attributes, all of which have default values set

Looking for the most elegant Typescript solution for a function with optional parameters. The function doSomething(num, config?) takes a number and an optional config object with a few optional parameters. If the config type is defined as { acceptNegativ ...

Using Angular with THREE JS integration in Javascript

I am currently experimenting with Angular and facing a challenge that I can't seem to figure out. The issue I am encountering involves integrating a javascript code, SunLight.js, from the repository https://github.com/antarktikali/threejs-sunlight in ...

How can I utilize Pinia and TypeScript to set the State using an Action?

I have a Pinia + TypeScript store named user.ts with the following structure: import { User } from 'firebase/auth'; import { defineStore } from 'pinia'; export const useUserStore = defineStore('user', { state: () => ( ...

Link the Angular Material Table to a basic array

Currently facing a challenge with the Angular Material table implementation. Struggling to comprehend everything... I am looking to link my AngularApp with a robot that sends me information in a "datas" array. To display my array, I utilized the following ...

What could be causing Bootstrap to fail in my Angular implementation?

It seems like I have successfully imported everything... angular.json: { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects ...

Is there a way to retrieve a React.Component class by calling a function?

I came across this interesting post: How can I return a class from a TypeScript function? In the linked post above, there is an example of working code: export class Foo {} // Foo is exported export let factory = () : Foo => { // it could be return ty ...

Tips for creating a TypeScript generic that ensures no SubType property is overly restricted

I am looking to create a function that can generically return a partial object of a specific type, where the object has an ID property. When working with a concrete type, such as the example below, the function works smoothly: type Person = { id: string; ...

What is the correct way to properly parse JSON attributes containing slashes?

I have 2 Custom Interfaces: DataModel.ts export interface Entry{ id: number, content: Note } export interface Note{ message: string } These interfaces are utilized in typing the HttpClient get request to fetch an array of Entries: DataService.ts getE ...

Angular SignalR template for ASP.NET Core 6

Is there a specific .NET template for an operational ASP.NET Core 6 application with SignalR and an Angular ClientApp using WebSockets transport? I've managed to only make the ServerSideEvents transport function. The 'dotnet new angular' co ...

Error in Angular 2 after transition to @types: encountering "require" name not found issue

After transitioning my project from old typings to types-publisher, I have successfully resolved most of my dependencies. However, I am consistently encountering an error that reads Cannot find name 'require'. Below is a snippet from my tsconfig. ...

404 error received from Angular 2 API call despite successful testing of service

I've been attempting to make a web service call from my Angular 2 application. private baseUrl: string = 'http://localhost:3000/api'; getPatterns(): Observable<Pattern[]> { const patterns$ = this.http .get(`${this.baseUrl ...

Using TypeScript and Angular to retrieve a service instance within a static function

I have a situation where I am trying to access an instance property within a static method in my utility class. Here is an example code snippet: export class DataUtil { constructor(public core:CoreStructureService){ } static fetchContact(id:s ...

Having issues with the Carousel feature in Bootstrap 5.3.1 while using Angular version 15

I'm currently in the process of setting up a carousel on my homepage. It seems like everything is in place, but there's something missing. The initial image, text, and arrows all display properly, but they are non-functional. I have correctly imp ...

Angular 8 - How to Intercept and Customize HTTP Error Responses

I am looking for a way to intercept and edit an HttpResponse that is of type HttpErrorResponse, specifically with a status code of 500. I want to change the status to 200 and populate its body so that I can treat it as a successful HTTP call in the subsc ...

Tips for efficiently using the debounce feature of valueChanges in reactive forms to prevent entering a patching loop while saving for the first time

Currently, I am working on implementing a debounce feature for my form fields. The challenge arises when dealing with a fresh form that lacks an ID. Upon creating and retrieving the record from the database, it becomes necessary to update the form with the ...

The requested property map cannot be found within the Array

I am working on a project using redux with react typescript. I have an external JSON file that contains employee data categorized by department id. To properly map the data with types in my application, I have created specific types. Check out this demo o ...

Most effective methods for validating API data

Currently, I am working on developing an api using nestjs. However, I am facing some confusion when it comes to data validation due to the plethora of options available. For instance, should I validate data at the route level using schema validation (like ...

Error in Angular 16.2.0: Signal TypeError <mySignal> cannot be executed as a function

I have a service that has a signal containing a list of Customers (interface). Whenever I call a method to retrieve the signal content, I encounter an issue: ERROR TypeError: this.customers is not a function at Object.upsertCustomer [as next] Here is th ...