In Angular, additional code blocks are executed following the subscription

I am facing an issue with my file upload function. After the file is uploaded, it returns the uploaded path which I then pass to a TinyURL function

this.tinyUrl.shorten(data.url).subscribe(sUrl => { shortUrl=sUrl;});
. However, there is a delay in receiving the sUrl and the subsequent code gets executed before that. I want to ensure that the next code is not executed until the sUrl is returned.

handleUpload(file) {
    let promise = new Promise((resolve, reject) => {
      const contentType = file[0].type;
      const bucket = new S3(
        {
          .....
        }
      );
      .....
      bucket.upload(params, (err, data)=> {
        if (err) {
       
          return false;
        } else {
          if (data.url) {
            this.tinyUrl.shorten(data.url).subscribe(sUrl => {
              shortUrl=sUrl;
            });
          }
          resolve(this.FileUploadImage);
        }
      });
      setTimeout(() => {                        
       
      }, 4000);
    });
 

  }

If anyone has a solution, I would appreciate it. Thank you!

Answer №1

When you subscribe to something, it happens asynchronously. This means that everything outside of the subscription will be executed first, just like you saw. If you need something to occur after the subscription returns a value, it should be done inside the subscription block, similar to Taras' approach:

this.tinyUrl.shorten(data.url).subscribe(sUrl => {
  shortUrl=sUrl; 
  this.FileUploadImage();
});
this.nextMethod();

The line this.FileUploadImage() will only run once the subscription receives a response. On the other hand, this.nextMethod(); is executed immediately, even before the subscription begins.

It's important to note that subscribing in this manner is considered deprecated. For more information, refer to this discussion on Stack Overflow: Subscribe is deprecated: Use an observer instead of an error callback.

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

Is it feasible to deliver push notifications from one application on a single device to the identical application on a different device using Ionic 4?

Is it possible to send push notifications from one app on a device to the same app on another device using Firebase Cloud Messaging in Ionic 4? I'm hoping to be able to create a text and a simple button in one app, and automatically send FCM push not ...

Tips for preventing circular dependencies in JavaScript/TypeScript

How can one effectively avoid circular dependencies? This issue has been encountered in JavaScript, but it can also arise in other programming languages. For instance, there is a module called translationService.ts where upon changing the locale, settings ...

Troubleshooting the Issue with Conditional Rendering in Nextjs & TypeScript

Struggling with rendering a component conditionally. I have a drawHelper variable and a function to toggle it between true and false. The component should render or not based on the initial value of drawHelper (false means it doesn't render, true mean ...

Greetings, I am currently using Angular version 3n 2 rc5 and I am hoping to execute a function called "change" that will perform two separate functions

I am working on a piece of code where I need to assign a value to a variable and then trigger a function simultaneously. I have attempted the following approach, but I am not sure if it is correct. Can someone provide some assistance? view.html <input ...

Tips on how to dynamically uncheck and check the Nebular checkbox post-rendering

I incorporated a nebular theme checkbox into my Angular 8 App. <nb-checkbox [checked]="enable_checked" (checkedChange)="enable($event)">Enable</nb-checkbox> I am able to update the checkbox using the Boolean variable "enable_checked". Initia ...

Rearranging data received from an Observable

TL;DR I am working on an Angular app where I need to shuffle an array of names retrieved from a network request and ensure that each group of 6 names selected is unique. However, I noticed duplicates in the selections. Here's a CodePen example using o ...

How can you connect a property to the output of a method in Vue.js when working with TypeScript and vue-property-decorator?

I'm working with a TypeScript single file vue component. I've encountered an issue where the template does not display the values returned by certain component methods. Here's a snippet of the template: <div class="order-items"> ...

Implement a class attribute to the parent <div> element using React and TypeScript

I'm trying to figure out how to achieve this task. I need to assign a class upon clicking on an element that is not directly in my code, but rather in one of its parent elements. My initial thought was to accomplish this with jQuery using the followi ...

Merging declarations fails to function properly following the release of the npm module

The file core.ts contains the definition of a class called AnyId. In another file named time.ts, more methods are added to the AnyId class. This is achieved by extending the type of AnyId using declaration merging: declare module './core' { in ...

Creating a personalized menu using Nextron (electron) - Step by step guide

I'm currently in the process of developing an app with Nextron (Electron with Nextjs and Typescript). Although I have the foundation of my Next app set up, I've been encountering issues when attempting to create a custom electron menu bar. Every ...

Struggling with transferring data rows between tables in Angular with Angular Material

I have implemented a data table using angular material with initial data rows. Additionally, I have included an empty data table where rows can be transferred from the first table. Transferring rows from the first table to the second table is functioning ...

What causes old data to linger in component and how to effectively clear it out

Fetching data from NGXS state involves multiple steps. First, we define the state with a default list and loading indicator: @State<CollectionsStateModel>({ name: 'collections', defaults: { collectionList: [], (...), isListLoading: true, ...

Crystal-clear TextField component in Office UI Fabric

Seeking advice on how to clear a masked text field from Office UI Fabric using a button. Does anyone have a solution for this? I attempted to set the value using a state, but unfortunately, it did not work as expected. ...

Encountering TS2322 error when defining a constructor in Angular 2 with ag-grid

Currently, I am following a tutorial I stumbled upon online titled Tutorial: Angular 2 Datatable with Sorting, Filtering and Resizable Columns. It appears to be the most straightforward guide to help me get started with the ag-grid library before delving d ...

Struggling to extract the hours and minutes from a date in IONIC: encountering an error stating that getHours is not a recognized

I encountered an issue while trying to extract the hours and minutes from a date in Ionic. Below is the code snippet from my .html file : <ion-datetime displayFormat="HH:mm" [(ngModel)]='timeEntered1' picker-format="h:mm"></ion-date ...

The confirm alert from Material UI is being obscured by the dialog

How can I ensure that a material ui dialog does not hide the alert behind it when confirming an action? Is there a way to adjust the z index of the alert so that it appears in front of the dialog? import Dialog from "@material-ui/core/Dialog"; i ...

Is there a way to update a BehaviorSubject value without using the next method?

I am looking for a solution to update the value of my BehaviorSubject without causing any subscriptions to be triggered. I attempted the following: this.mySubject = new BehaviorSubject(newVal); Unfortunately, this approach also removes all existing subs ...

Transform a standard array of strings into a union string literal in TypeScript

I'm currently developing a module where users can specify a list of "allowable types" to be utilized in other functions. However, I'm encountering challenges implementing this feature effectively with TypeScript: function initializeModule<T ex ...

The server has access to an environment variable that is not available on the client, despite being properly prefixed

In my project, I have a file named .env.local that contains three variables: NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY=pk_test_<get-your-own> MAGIC_SECRET_KEY=sk_test_<get-your-own> TOKEN_SECRET=some-secret These variables are printed out in the file ...

Preserving type information in TypeScript function return values

Wondering how to make this code work in TypeScript. Function tempA copies the value of x.a to x.temp and returns it, while function tempB does the same with x.b. However, when calling tempA, the compiler seems to forget about the existence of the b field ...