Obtain the POST request response in Angular 6

Currently, I am utilizing Angular to create a user interface that interacts with a REST API. Within the function below, my process involves adding a new project via a POST request, followed by the addition of a series of aliases inputted by the user in the form. Subsequently, these aliases are added to the project and then the selected apps list is retrieved where their IDs are located and finally added to the project. Take a look at the following post calls:

addProject(name: string, description: string): void {

    // Adding a new project
    let newProjectId: number;
    let newAliasId: number;
    let url = this.baseUrl + "/projects";
    this.httpClient.post<Project>(url,
        {'name': name, 'description': description }, 
        httpOptions).subscribe((data: any) => { newProjectId = data['result']['id'];})

    // Adding the aliases 
    for (let entry of this.aliasList) {
        let UrlAddAlias = this.baseUrl + "/alias";
        this.httpClient.post(UrlAddAlias, {'alias': entry }, httpOptions)
        .subscribe((data: any) => { newAliasId = data['result']['id'];});
        // Adding aliases to the new project
        let UrlAliasToProject = this.baseUrl + `/projects/${newProjectId}/alias`;
        this.httpClient.post(UrlAliasToProject, {"alias_id" : newAliasId}, httpOptions)
        .subscribe((data: any) => { console.log("alias added to project");});
    };

    // Adding the selected applications to the new project
    for (let entry of this.selectedApps) {
        let Urlapp = this.baseUrl + `/apps/name/${entry}`;
        let appId;
        this.httpClient.get(Urlapp).subscribe(data => { appId = data['result']['id']; });
        let urlappToProject = this.baseUrl + `/projects/${newProjectId}/apps`;
        this.httpClient.post(urlappToProject, {'app_id': appId });
    };
}

The issue arises when attempting to retrieve the values for newProjectId and newAliasId. The error message encountered is as follows:

Object { headers: {…}, status: 405, statusText: "Method Not Allowed", url: "http://api.com/v1/projects/undefined/alias", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://api.com/v1/projects/undefined/alias: 405 Method Not Allowed", error: "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n<title>405 Method Not Allowed</title>\n<h1>Method Not Allowed</h1>\n<p>The method is not allowed for the requested URL.</p>\n" }

Although I can successfully log the values using console.log, they appear as undefined outside of this context.

Answer №1

The .subscribe function operates asynchronously, meaning that any code written after it will execute before the callback function is called... much like using setTimeout.

setTimeout(() => console.log('second'));
console.log('first');

To ensure everything happens in the proper order, you can encapsulate all subsequent actions within the .subscribe method:

.subscribe((data: any) => {
  newProjectId = data['result']['id'];

  for (let entry of this.aliasList) { ...
});

If feasible, consider redesigning your API to eliminate multiple requests and have the post function manage everything internally.

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

Using TypeScript to include a custom request header in an Express application

I am attempting to include a unique header in my request, but I need to make adjustments within the interface for this task. The original Request interface makes reference to IncomingHttpHeaders. Therefore, my objective is to expand this interface by intr ...

Is there another way to implement this method without having to convert snapshotChanges() into a promise?

When trying to retrieve cartIdFire, it is returning as undefined since the snapshot method is returning an observable. Is there a way to get cartIdFire without converting the snapshot method into a promise? Any workaround for this situation? private asyn ...

What is the process of importing an npm module into an Angular application?

While searching for a solution, I stumbled upon this npm package that allows us to group arrays according to our needs. I want to integrate this package into my Angular application for grouping arrays. What is the correct way to import this package into ...

Do I need to use Node.js for Angular 2, or can I run it on an Apache server instead

Can XAMPP or Apache be used instead of the Node.js npm server when working with Angular 2? ...

Divs are not being organized into rows correctly due to issues with Bootstrap styling

I have implemented Bootstrap in my Angular application. The stylesheet link is included in my Index.html file as follows: <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css"> In addition to that, I have listed Bootstrap a ...

Difficulty encountered when trying to apply a decorator within a permission guard

I'm a newcomer to Nestjs and I am currently working on implementing Authorization using Casl. To achieve this, I have created a custom decorator as shown below: import { SetMetadata } from '@nestjs/common'; export const Permission = (acti ...

Tips for customizing the `src/app/layout.tsx` file in Next.js 13

I am looking to customize the layout for my /admin route and its child routes (including /admin/*). How can I modify the main layout only for the /admin/* routes? For example, I want the / and /profile routes to use the layout defined in src/app/layout.ts ...

The latest version of fork-ts-checker-webpack-plugin, version 5, cannot be reached from @vue/cli-plugin-types

Currently, I am updating the build container in my project from node:10-alpine to node:14-alpine. However, when I run npm ci (after rebuilding package-lock.json), I encounter the following error: npm ERR! fork-ts-checker-webpack-plugin-v5 not accessible fr ...

Creating a personalized theme for Material UI 5.0 using Typescript with React

Having some trouble customizing a theme in Material UI 5.0 with typescript. theme.ts import { createTheme } from '@mui/material'; declare module '@mui/material/styles' { interface Theme { custom: { buttonWi ...

What is the best way to redirect to a different page within a function using "react-router-dom" version "^6.21.1"?

Having trouble redirecting to another page and unable to use useNavigate() inside the function as it's not a component. Redirect function also doesn't seem to be working. How can I achieve the redirection? import { redirect, useNavigate } from &q ...

Ways to customize background color for a particular date?

I have been using the fullcalendar npm package to display a calendar on my website. I am trying to figure out how to set a background color for a specific selected date. I tried looking into this issue on GitHub at this link. However, it seems that dayRe ...

Issue encountered during testing does not appear in final compilation and prevents tests from executing

Embarking on my maiden voyage with Angular 5... Currently in the process of setting up a Jasmine test tutorial found at this link: https://angular.io/guide/testing. However, upon initiation, an error throws me off course: ERROR in src/app/pizzaplace.serv ...

Troubleshooting TypeScript errors related to ReactNode post-upgrade to Create React App v5

Since upgrading to Create React App version 5, I've been encountering errors like the one below: TS2786: 'OutsideClickHandler' cannot be used as a JSX component. Its instance type 'OutsideClickHandler' is not a valid JSX element. ...

The TypeScript compiler is unable to locate the identifier 'Symbol' during compilation

Upon attempting to compile a ts file, I encountered the following error: node_modules/@types/node/util.d.ts(121,88): error TS2304: Cannot find name 'Symbol'. After some research, I found that this issue could be related to incorrect target or l ...

The Typescript errors is reporting an issue with implementing the interface because the type 'Subject<boolean>' is not compatible with 'Subject<boolean>'

Creating an Angular 2 and Typescript application. I am facing an issue with an abstract class within an NPM package that I am trying to implement in my app code. Everything was functioning correctly until I introduced the public isLoggedIn:Subject<bool ...

Is there a syntax available for type annotation of arrays created from pre-declared variables?

According to my standards, all possible annotations are required in TypeScript. Therefore, TypeScript-ESLint is prompting me to annotate the `[ responseData, cognitoUser ]`. However, when I try to use the syntax `[ responseData1: ResponseData1, responseD ...

Generate streams from a changing collection

Currently, I have a situation like this: onValueChange() { let someObj = //dynamically created this.processUsers(someObj); } processUsers(someObj) { from(Object.keys(someObj)) .pipe( concatMap(key => this.getUsers(key) ) .subscr ...

Obtaining results from several observable requests within a function

A function is currently operational, functioning by setting a value in the component when called (user.userImage). getLoggedInUserPhoto() { this.adalService.acquireToken('https://graph.microsoft.com') .subscribe(token => { let header = ...

Angular: facing difficulty displaying static html pages on server, although they render correctly when run locally

Within my Angular project, I have stored a few static html files (specifically sampleText.html) in the src/assets/html folder. In one of my components, I am attempting to fetch and display this file. The following code is being used for this purpose. Every ...

Is it possible to perform a HTTP POST request using Angular by opening a new window?

I'm facing some challenges while trying to make an HTTP post request in my angular app from the right-sidebar component. Whenever a user clicks on a button, this function is triggered: //right-sidenav.component.html info() { this.infoService.getI ...