Tips for utilizing async/await in conjunction with the pipe map function of an observable?

When I post something to the database, I need to retrieve certain data in the response. If that specific data is missing, I have to make another query using await/async. However, I am facing an issue with this setup when debugging the code. The implementation looks like this:

// Service (Endpoints changed)
public login(username: string, password: string) {
    let loginDto = { info: new LoginDto(username, password) };
    return this.http.post('https://jsonplaceholder.typicode.com/posts', { title: 'Angular POST Request Example' }).pipe(
      map(response => {
        return this.processLoginResponse(response);
      })
    );
}

private async processLoginResponse(response) {
    let permissions = await this.getPermissionsFromAPI(116677);
    this._user = {username: 'Jhon', permissions: permissions};
    return this._user
  }

private getPermissionsFromAPI(userId): Promise<any> {
    return this.http.get('https://jsonplaceholder.typicode.com/todos/1').toPromise();
  }

// Component
onSubmit(e) {
    const { username, password } = this.formData;
    this.authService
      .login(username, password)
      .subscribe(
        data => {
          data.then(x => console.log(x));
          // things
        }
      );
  }

Answer №1

To improve the code, consider utilizing observables instead of promises for a more effective approach. By incorporating rxjs operators like switchMap, you can easily make subsequent requests. With this method, you can achieve the desired outcome without having to rely on async/wait:

import { HttpClient } from '@angular/common/http';
import { switchMap } from 'rxjs/operators';
import { Observable } from 'rxjs';

export class UserService {
  constructor(private http: HttpClient) {}

     public loginUser(username: string, password: string) {
           let user = { info: new UserDto(username, password) };
           return this.http.post('https://jsonplaceholder.typicode.com/posts', { title: 'Angular POST Request Example' }).pipe(
                switchMap((response) => {
                    return this.fetchPermissions(response);
                })
              );
        }
        
    fetchPermissions(userId): Observable<any> {
          return this.http.get('https://jsonplaceholder.typicode.com/todos/1'); 
     }

}


onFormSubmit(event) {
    const { username, password } = this.formData;
    this.userService
      .loginUser(username, password)
      .subscribe(
        data => {
          data.then(result => console.log(result));
          // additional actions here
        }
      );
}

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

Tips for customizing the ion-alert header in Ionic framework

I have recently created an alert controller and am struggling to customize the appearance of the header within the alert popup. Despite going through the documentation, I have not been able to find a suitable solution. async customizeAlert(header, subHea ...

steps for retrieving final outcome from forkJoin

I am currently working with an array of userIds, such as: ['jd', 'abc']. My goal is to loop through these userIds and retrieve full names using an API. Ultimately, I aim to transform the initial array into [ {userId: 'jd', nam ...

Set the mat-option as active by marking it with a check symbol

Currently, I am utilizing mat-autocomplete. Whenever a selection is made manually from the dropdown options, the chosen item is displayed with a distinct background color and has a checkmark on the right side. However, when an option in the dropdown is se ...

Searching for a foolproof oauth framework that includes efficient refresh tokens

Currently, I am implementing oauth with refresh tokens for my Angular application and have a specific set of requirements: Automatically refresh the token when 5% of its time is remaining Handle situations where there is a loss of internet connection (re ...

cannot process post request due to authentication header

I'm facing an issue in Angular 4 when I try to make a POST request to the API with an Authorization header. addPost(body): Observable<any>{ const url = 'https://xxxxxx'; return this.http.post(URL, body, this.options) ...

Should I choose JavaScript or TypeScript for Angular 2.0?

What is the best approach for creating an Angular 2.0 application? Should it be done with JavaScript or TypeScript? I'm struggling to get started with Angular 2.0 using TypeScript, as it's quite different from JavaScript. ...

Troubleshooting Memory Address Concerns in Unit Testing for Moment Date

Having trouble with testing a method that utilizes the moment.subtract() function to remove one day from the current date. The issue lies in the fact that the subtract method provided by Moment only alters the date without creating a new memory address loc ...

Importing Typescript modules by specifying their namespace instead of using a function

I have been working on a project where I needed to generate typings from graphql using the gql2ts library. In the gql-2-ts file, I initially used a namespace import for glob, which resulted in TypeScript showing me an error as intended. I then switched the ...

Angular integration with Fine Uploader

I am facing a challenge in incorporating the fineuploader library into Angular 4. A post on provided some insight, but it seems to be aimed at Angular 2. Given the updates in Angular since version 4, I require further guidance. Returning to my issue: Fin ...

What are the steps to code this in Angular14 syntax?

Here's the code snippet: constructor(obj?: any) { this.id = obj && obj.id || null; this.title = obj && obj.title || null; this.description = obj && obj.description || null; this.thumbnailUrl = obj && obj.thumbnailUrl || null; this. ...

Utilizing Lazy Loading for the search HomeComponent, which is not being utilized within the module

I'm facing an issue with Lazy Loading in Angular. I have a module called ShopCartModule that needs to be implemented using Lazy Loading. In addition to the ShopCartModule, I also have the AppModule and the CoreModule. This is my AppModule: @NgModul ...

Guide to resolving a Promise that returns an array in TypeScript

My goal is to retrieve an array in the form of a promise. Initially, I unzipped a file and then parsed it using csv-parse. All the resulting objects are stored in an array which is later returned. Initially, when I tried returning without using a promise, ...

There is no such thing as Magic Sequelize Function

I am new to TypeScript and have recently started learning about the Sequelize ORM model. While I had worked on a few projects with Sequelize using plain JavaScript before, I decided to give it a shot with TypeScript this time. However, I've been facin ...

Using TypeScript to create a generic type that wraps around HTMLElements

I attempted to execute this action, however the assignment to this.element is not working and I am unsure why. class Elem<T> { public element : T; constructor(typeElement:string){ this.element = document.createElement(typeElement); ...

The .ts document is not recognized as a TypeScript module

Check out this SystemJS + TypeScript plunk, which was created using the official Angular plunk template. An error is being thrown: (SystemJS) SyntaxError: Missing initializer in const declaration at eval () ... This error occurs when the .ts file is t ...

Using React Testing Library with TypeScript revealed issues with ES6 modules causing test failures

I am currently working on a small project that involves React, Typescript, and Mui v5. The application is relatively small and uses the default Create React App setup. Although I am new to unit and integration testing, I am eager to make use of the tools ...

Creating a TypeScript object with fields arranged in the order they were added

Currently, I find myself in a perplexing predicament where I am required to construct an object with unspecified properties that must maintain the order of insertion. This necessity arises from the fact that I need to transmit this object to a server over ...

The code at line 646 in fs.js uses `binding.open` to open the specified path, converting it to a long path using `

Having recently transitioned from Angular 2 to Angular 5, I am facing an issue while running the npm install command. The error message I encounter is as follows: fs.js:646 return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode); ...

Exploring the application of UI extension with Typescript in Cytoscape.js

Is it possible to use Cytoscape UI extensions in Typescript? I am able to use the Layout extension, but when I try to implement other extensions like https://github.com/cytoscape/cytoscape.js-cxtmenu, I encounter issues as the function cy.cxtmenu( defaults ...

Exploring nested objects with ReactJS and mapping through them

After receiving an object from the backend, I am loading it into a Redux property inside my Component called user. The schema of this object is as follows: { user: 'root', perm: [ "admin", "write", "read", "nodata ...