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

Utilizing Dynamic Variables in Angular 4 Templates

Hey everyone, I recently created an Angular 4 app and developed a component called Contentholder. The Contentholder consists of HTML & CSS to display the content holder that I am utilizing. When I include <content-holder></content-holder>, ...

Run a function from an alternate element

I have successfully created a grid with a button that enables me to control a timer. When I click on the start button in the grid on the home page, the timer begins counting the time. By using a service, I am able to determine whether the timer is active ...

Swiping in Angular2 gets a new twist with Swiper typings

Having trouble importing typings for Swiper into my Angular 2 project. After installing Swiper and its typings using npm, I tried including Swiper in my component like this: import { Swiper } from 'swiper'; However, Atom displays an error: ...

What is the best way to verify both a null value and a length simultaneously within a template condition?

There is a data that can be null or an empty array, but the template should still be rendered if leaseApDto is not null or has a length greater than 0. I attempted to use the condition model.leaseApDto !== null || model.leaseApDto.length !=== 0, but they ...

What is the best way to filter an array of objects and store the results in a new variable list using typescript?

On the lookout for male objects in this list. list=[ { id: 1, name: "Sam", sex: "M"}, { id: 2, name: "Jane", sex: "F"}, { id: 3, name: "Mark", sex: "M"}, { id: 4, name: "Mary, sex: "F& ...

Display Facebook events using AngularJS technology

I am looking to showcase events on my website. Currently, I am fetching events from Facebook utilizing the following code: In my infos.service.ts file: getEvents(link: string): Observable<any>{ let id = link.split('facebook.com/')[1].sp ...

The error message "Unable to access property 'open' of an undefined menu" is being displayed in a TypeScript code

I am facing an issue with the action in my menu. For this project, I am using a material menu and icons. The main menu code appears as follows: <mat-menu #rootMenu="matMenu" [overlapTrigger]="false"> <ng-template matMenuContent let-element="ele ...

The type 'string' cannot be assigned to type 'ImageSourcePropType'

Context Attempting to utilize a SVG component in React Native with the xlinkHref property within an Image tag. The SVG file was converted into a React Native Component (TSX) using the tool provided at . While simple SVG icons have been successfully used be ...

Angular2: Maintaining a continuous connection for a child component to receive input from the parent component post onInit

I'm currently working on integrating an error message component into another parent component. The child component, which displays the error message, has an input attribute that the parent component uses to pass the error message. However, I've e ...

Combining Several Middleware Functions in NextJs 13 for Authentication and Localization

Important Note If you are interested in exploring my code further, you can find the repository here. To access the specific code for the ott-platform, navigate to apps/ott-platform. Please make sure to create an account on Clerk and input your Clerk key i ...

Enhancing TypeScript functionality by enforcing dynamic key usage

Is there a way to ensure specific keys in objects using TypeScript? I am attempting to define a type that mandates objects to have keys prefixed with a specific domain text, such as 'create' and 'update': const productRepoA: Repo = { } ...

Managing errors with the RxJS retry operator

I'm facing an issue with my RxJS code where I need to continuously retry a data request upon failure while also handling the error. Currently, I am using the retry operator for this purpose. However, when attempting to subscribe to the retry operator ...

typescript library experiencing issues with invalid regex flags in javascript nodes

I am facing an issue while attempting to import a plain JavaScript module into a Node application written in TypeScript. The error below is being thrown by one of the codes in the JavaScript module. b = s.matchAll(/<FILE_INCLUDE [^>]+>/gid); Synta ...

Importing components in real-time to generate static sites

My website has a dynamic page structure with each page having its unique content using various components. During the build process, I am statically pre-rendering the pages using Next.js' static site generation. To manage component population, I have ...

Tips for using an ArrayBuffer to stream media in Angular

Currently, I am facing an issue while transferring data from my backend with nodeJS to Angular. Everything seems to be working fine except for one problem - my media files are not functioning properly in my code. To resolve this, I have implemented Blob fi ...

Change the value of the checked property to modify the checked status

This is a miniCalculator project. In this mini calculator, I am trying to calculate the operation when the "calculate" button is pressed. However, in order for the calculations to run correctly in the operations.component.ts file, I need to toggle the val ...

You are unable to compile a module in Visual Studio Code unless you provide the --module flag

I am facing an issue with my TypeScript code file that appears to be a common error, but I'm struggling to resolve it. This problem is new to me as I am still getting acquainted with Visual Studio Code. Cannot compile modules unless the '--modul ...

Error encountered: ExpressionChangedAfterItHasBeenCheckedError when trying to load the loading indicator

I encountered an issue with my loading indicator that I cannot seem to resolve: LoadingIndicatorComponent.html:2 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'hidden: true&ap ...

What could be causing ngClass to constantly invoke a function without end?

I am currently working on a feature to add a class based on the presence of a value in storage or a specific set value. I am using [ngClass] to achieve this, but for some reason, the function that checks the storage is being called indefinitely. What could ...

What causes the template to refresh when the input remains unchanged while employing the OnPush strategy?

Trying to understand this situation: @Component({ selector: 'app-test', template: `value: {{value|json}} <button (click)="setValue()">set</button>`, changeDetection: ChangeDetectionStrategy.OnPush }) export class TestComponent ...