How can I generate a unique ID for a contact database in Angular 2 when adding a new function?

I am currently working on developing a Contact Form, but I am facing an issue with generating a new ID for the POST function. Each time I try to set a new ID, I receive the following output:

{
    _isScalar: false, 
    operator: Object {...}, 
    source: Object {...}
}

Is there any solution to obtain a new ID that follows a sequence like 1, 2, 3, and so on?

public Add = (Name: string, Nachname: string, Geburtsdatum: string, Strasse: string, Hausnummer: string, Postleitzahl: string, Wohnort: string): Observable<boolean> => {
    let id = this._http.get(this.actionUrl + 'getid', { headers: this.headers })
                       .map(res => res.json());

    var toAdd = JSON.stringify({ 
        Id: id, 
        Name: Name, 
        Nachname: Nachname, 
        Geburtsdatum: Geburtsdatum, 
        Strasse: Strasse, 
        Hausnummer: Hausnummer, 
        Postleitzahl: Postleitzahl, 
        Wohnort: Wohnort 
    });

    console.error(toAdd);

    var res = this._http.post(this.actionUrl, toAdd, { headers: this.headers })
                        .map(res => true)
                        .catch(this.handleError);

    console.error(res);
    return res;
}

Answer №1

One issue that stands out is the lack of subscribing to your http.get request. Without adding the subscribe call, the request will not be executed.

Furthermore, it's important to note that Observables are asynchronous by nature. This means you won't get the value back from the call as expected. Instead, you need to handle the response in the subscribe callback. Any logic dependent on that response should also be within that callback. You can chain multiple calls depending on each other using .flatMap.

public Add = (Name: string, Nachname: string, Geburtsdatum: string, Strasse: string, Hausnummer: string, Postleitzahl: string, Wohnort: string): Observable<boolean> => {
    return this._http.get(this.actionUrl + 'getid', { headers: this.headers })
        .map(res => res.json())
        .flatMap(res => {
            var toAdd = JSON.stringify({ 
                Id: res, // depends on what your getid call returns 
                Name: Name, 
                Nachname: Nachname, 
                Geburtsdatum: Geburtsdatum, 
                Strasse: Strasse, 
                Hausnummer: Hausnummer, 
                Postleitzahl: Postleitzahl, 
                Wohnort: Wohnort 
            });

            console.error(toAdd);

            return this._http.post(this.actionUrl, toAdd, { headers: this.headers })
                .map(res => {
                    console.log(res);
                    return true; // perhaps return the actual result?
                 }) 
                .catch(this.handleError);
        }
    );
}

The variable res being logged is an Observable, not the actual result from your database. Log the response inside the .map method, where you're currently returning true for some reason.

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

Sending Data from Angular 2 to a Node/Express Server using a POST Request

I am facing difficulties in identifying why my Angular 2 Typescript application is unable to send a successful HTTP request. Although I can successfully send POST requests through Postman, the front-end appears to have trouble connecting with the back-end. ...

Angular displaying a slice of the data array

After following the example mentioned here, and successfully receiving API data, I am facing an issue where only one field from the data array is displayed in the TypeScript component's HTML element. Below is the content of todo.component.ts file im ...

Router navigation does not trigger LifeCycle calls

I currently have the following routes set up: {path:'home', component:HomeComponent, canActivate: [AuthGuard]}, {path:'profile', component:UserProfileComponent, canActivate: [AuthGuard] }, Additionally, in my navbar.component, I hav ...

Unable to render information within the PrimeNG tree component

I've set a goal for myself to create a treeview using the PrimeNG Tree Component. Currently, I have a small service with the following method: TypeScript: getMenuDetails(parentID: number) { let url = this.serverURL + 'api/Nodes/' + pa ...

Steer clear of using Typescript to exclude certain sections of code from compilation

Is there a method to prevent certain code from being compiled by the Typescript compiler based on a variable that needs to be provided in the compiler command? This would be beneficial for developing multi-platform applications where the code is mostly sim ...

Steps to remove a particular view from an angular view container

Check out this live example at https://stackblitz.com/edit/angular-1acvol I've managed to create multiple views using a TemplateRef and attach them to the same ViewContainer. However, I'm struggling to find a way to remove a specific View from t ...

Angular: Connecting template data to different visual presentations

Looking for a solution to display data and map values to another presentation without needing complex ngIf statements or creating multiple components. Check out this sample: https://stackblitz.com/edit/angular-9l1vff The 'vals' variable contain ...

Angular 6 - Using properties in classes

Considering a component structured as follows: import { Component, OnInit, ViewChild } from '@angular/core'; @Component({ selector: '...', templateUrl: './...html', styleUrls: ['./...scss'] }) export class Te ...

Is it feasible to send FormData and an Image file together to a web API from an Angular 6 application?

Is it feasible to send both form data and an image file to a web API from an Angular 6 application? app.component.ts onSelectFile(event) { if (event.target.files && event.target.files[0]) { this.imageToUpload = event.target.files[0]; co ...

Guide on effectively utilizing @types/lodash for specific lodash.* libraries

To decrease the size of my Angular project bundle, I am individually installing and importing lodash libraries like lodash.clonedeep and other lodash.*. However, I am losing type definitions for these since they do not work with the @types/lodash npm packa ...

Could routerLinkActive be used to substitute a class rather than simply appending one?

I have a navigation bar icon that links to an admin route. I want this icon to change its appearance when on that specific route. To achieve this, I can simply replace the mdi-settings-outline class with mdi-settings, displaying a filled version of the sam ...

tslint is flagging an error related to cyclomatic complexity

Within my Angular 8 project, the following dependencies are utilized: "codelyzer": "^5.1.0", "ts-node": "~8.3.0", "tslint": "~5.19.0", Upon executing: ng lint myapp --fix=true An error is raised stating: ERROR: ...html:428:106 - The cyclomatic complex ...

Is it possible to utilize ngIf to reuse a component when encountering a 404 error? How can the error be captured?

In my app-routin.module.ts file, I have a root component named HomeComponent that I reuse for unknown routes. const routes: Routes = [ { path: '', component: PrimaryComponent, data: { breadcrumb: 'PRIMARY'}, children: [ { p ...

Adding text in CKEditor with Angular while preserving the existing formatting

To add my merge field text at the current selection, I use this code: editor.model.change(writer => { var position = editor.model.document.selection.getFirstPosition(); // trying to connect with the last node position.stickiness = 'toP ...

Having trouble sending a string to the formGroup

1. I am trying to iterate through an array *ngFor="let item of myformNameArray" Assuming myformNameArray.length is 3, if I console item, it will display: myFormName1 myFormName2 myFormName3 I have already created form groups in my TypeScript component. ...

rxjs subscriptions in Angular

When setting up a subscription in Angular, I am declaring it as follows: counterSubscription: Subscription However, an error is being thrown stating: Property 'counterSubscription' has no initializer and is not definitely assigned in the const ...

Is there a way to determine the position of the highlighted text within a textarea?

Is there a simple way to calculate the position of the selected text within a textarea using vanilla JavaScript or Angular (possibly with a directive)? This is important in order to display a div with a popup above the selected text. Coordinates are need ...

Blast information to Observable

To view the code sample, visit the following link: stackblitz In my data service, data is fetched asynchronously from a global object (in the actual project, data is emitted via EventEmitter). The structure of the service is as follows: import { Injectab ...

What's up with @use behaving oddly in Angular + SASS imports from node_modules?

Encountering an issue when importing styles using @use in my Angular project. In the styles.scss file, @use "@angular/material" as mat; works perfectly. However, @use "ngx-popperjs" as ngx-popperjs; results in an error stating "Can& ...

Is there a setFieldsValue function available in Chakra UI?

Is there a function similar to ANTD's setFieldsValue in Chakra UI? I wanted to populate my form with default values from an API call upon initial rendering. The Chakra UI documentation suggests using Formik, but I'm wondering if there is a more ...