The form's second part is missing an object definition

When I refer to property, I'm specifically talking about a house. This is a platform for listing properties.

I am currently working on an application using Angular (with a Laravel API backend). The form for submitting a property is divided into 3 steps. In the first step, within my advert service, I assign the model data returned as the current property. I can successfully log this data to the console.

However, when I attempt to log it upon submission of the second part of the form, I encounter an undefined error. I need the ID from this object to send it to the URL.

AdvertService

createAdvert(userId: number, property: Property) {
    return this.http.post(this.baseUrl + userId + '/store', {property}).pipe(
      map((response: any) => {
          this.currentProperty = response;
          console.log(response);
      })
    );
}

When I inject the service into the second part of the form and try to access the current property with a console.log, I receive 'undefined'.

submitPayment() {
    const currentProperty = this.advertService.currentProperty.id;
    console.log(currentProperty);
    if (this.advertPaymentForm.value) {
        this.payment = (Object.assign({}, this.advertPaymentForm.value));
        console.log(this.payment);
        this.advertService.createAdvertPayment(currentProperty.id, this.payment).subscribe(data => {
            this.alertify.success('Success');
        }, error => {
            this.alertify.error(error);
        });
    }
}

Property Model

export interface Property {
    id?: number;
    town?: string;
    county?: string;
    address: string;
    postcode: string; // corrected spelling
    eircode: string;
    property_type: string;
    selling_type: string;
    price: number;
    bedrooms: number;
    bathrooms: number;
    size: number;
    building_energy_rating: string;
    description: string;
    user_id: number;
}

Edit. Data from createAdvert console:

https://i.sstatic.net/tEWLH.png

Any thoughts on what could be causing the issue here?

Full advert.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { Property } from '../_models/property';
import { User } from '../_models/user';
import { Payment } from '../_models/payment';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AdvertService {

  baseUrl = environment.apiUrl + 'advertisement/';
  currentProperty: any;

  constructor(private http: HttpClient) { }

  createAdvert(userId: number, property: Property) {
    return this.http.post(this.baseUrl + userId + '/store', {property}).pipe(
      map((response: any) => {
          this.currentProperty = response;
          console.log(this.currentProperty);
      })
    );
  }

  createAdvertPayment(propertyId: number, payment: Payment) {
    return this.http.post(this.baseUrl + propertyId + '/payment', {payment});
  }
}

Full advert-payment.component.ts (where the service is injected into)

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { AdvertService } from '../_services/advert.service';
import { AlertifyService } from '../_services/alertify.service';
import { AuthService } from '../_services/auth.service';
import { Payment } from '../_models/payment';

@Component({
  selector: 'app-advert-payment',
  templateUrl: './advert-payment.component.html',
  styleUrls: ['./advert-payment.component.css']
})

export class AdvertPaymentComponent implements OnInit {
  advertPaymentForm: FormGroup;
  model: any;
  payment: Payment;
  constructor(private advertService: AdvertService, private alertify: AlertifyService, public authService: AuthService,
    private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.createAdvertPaymentForm();
  }

  createAdvertPaymentForm() {
    this.advertPaymentForm = this.formBuilder.group({
      town: ['', Validators.required],
      county: ['', Validators.required],
      billing_address: ['', Validators.required],
      cardnumber: ['', Validators.required],
      month: ['', Validators.required],
      year: ['', Validators.required],
      cvv: ['', Validators.required],
    });
  }

  submitPayment() {
    const currentProperty = this.advertService.currentProperty[0].id;
    console.log(currentProperty);
    if (this.advertPaymentForm.value) {
        this.payment = (Object.assign({}, this.advertPaymentForm.value));
        console.log(this.payment);
        this.advertService.createAdvertPayment(currentProperty.id, this.payment).subscribe(data => {
            this.alertify.success('Success');
        }, error => {
            this.alertify.error(error);
        });
    }
  }

}

Answer №1

Upon inspecting the code, it seems that you forgot to subscribe to

createAdvert(userId: number, property: Property)
in your component, leading to the currentProperty not receiving the value from the HTTP call.

Don't forget to include this subscription in your component's OnInit method:

ngOnInit() {
    this.createAdvertPaymentForm();
    this.advertService.createAdvert(YourUserId, UserProperty).subscribe(data => {
         console.log(data); // This will provide you with the data for `currentProperty`
     });
  }

In Angular, an http request returns an observable, so it is necessary to subscribe. If there are no subscribers to the observable, it will not be executed

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

Explaining the concept of prototypical reusability in JavaScript

I have been trying to understand the differences between the following two statements by reading various website tutorials, but I am still confused. Can someone please clarify? (Let's assume Person is a superclass/function of Employee) Employee.proto ...

What is the method for executing PHP code without the need for users to access the webpage?

Similar Query: Optimal method for running a PHP script on a schedule? I am in need of a solution where a PHP script can consistently fetch data from a single website, store it in a database on the server, and then update multiple other websites. The c ...

I am looking to merge two tables in MySQL using a many-to-one relationship and retrieve a customized JSON output similar to the example provided below. How can this

How can I perform a MySQL join on two tables (many to one) and generate a specific JSON output as demonstrated below? Note: Please do not label this as a duplicate. Although there is a similar previous question posted, there are distinct differences that ...

"Tricks to prompt the browser to refresh and load up-to-date content

Currently experiencing issues with my web browser (both on my laptop and smartphone). I am working on a website page (HTML, javascript) and have observed that my browser keeps retrieving cached information instead of loading the page each time, preventing ...

Is it possible to rearrange the node_modules directory?

Within the node_modules directory, there exists a large and extensive collection of modules. These modules are often duplicated in various sub-folders throughout the directory, with some containing identical versions while others differ by minor versions. ...

Developing a vanilla JavaScript web component with distinct HTML and JavaScript files

As I delve into creating vanilla JS web-components, I am exploring methods to keep the template HTML separate from the JS file, ideally in a distinct HTML file. I have examined various implementations of native JS web-component setups found notably here, ...

Encountering difficulties when trying to display a nested object with two levels of depth using

I am currently developing an application where I need to display a nested object with two levels using the map method. The data structure is as follows: const categories = [ { catName: "Education", subCategory: [ { subCatName: "Col ...

Build upon a class found in an AngularJS 2 library

Whenever I attempt to inherit from a class that is part of a library built on https://github.com/jhades/angular2-library-example For example, the class in the library: export class Stuff { foo: string = "BAR"; } And the class in my application: exp ...

Checking for selected checkboxes in Django admin's action-select using jQuery/JavaScript

In my Django admin project, I want to check if any of the action-select check-boxes have been selected in the change_list.html file using jQuery/JavaScript. Initially, I tried the following code: $(".action-select"); This gave me an array of all the inpu ...

What steps should be taken to ensure that the function triggered by @submit functions properly?

<!--html--> <div id="xxx"> <form action="#"> <input required type="text"> <input type="submit" @click="customFunction"> </form> </div> // ...

The frontend is not triggering the Patch API call

I am having trouble with my http.patch request not being called to the backend. This issue only occurs when I try calling it from the frontend. Oddly enough, when I tested it in Postman, everything worked perfectly. Testing the backend on its own shows t ...

Combining multiple .php files in a single div

Hey there! I have a piece of code that allows me to load a PHP file into a div. It's currently functional, but I'm facing a challenge where I need to load the next file into the same div. <script type="text/javascript"> $(function() { ...

What Occurs to Processed Messages in Azure Functions if Result is Not Output?

I have created an Azure function that is connected to the messaging endpoint of an IoT Hub in order to trigger the function for all incoming messages. The main purpose of this function is to decompress previously compressed messages using GZIP before they ...

Utilizing a DevOps pipeline to automatically adjust time formats when transmitting variable values as JSON payloads for deploying Azure resources using Terraform

My Terraform Deployment for Azure Resources includes a Budget with a specified start and end date. However, when I send the JSON Body/variable value from my Logic App through an http Post, DevOps alters the time format of the string values. Terraform requi ...

Tips for generating an arraylist from JSON using Kotlin

Recently delving into Kotlin, I've been attempting to craft an arraylist from a Json file. However, perplexingly, it's not functioning as expected. Here is the snippet of my Json data: { "bottomApp": "com.android.contacts", ...

Add the CSV information to the JSON data in my Angular application when subscribing to the API

I am faced with the task of merging data from a CSV file into the main JSON dataset that I utilize in my Angular application. To be more specific, I need to integrate life expectancies from the CSV file with their corresponding country entries within the ...

When attempting to asynchronously observe a datasource, the 'number' type cannot be assigned to the 'NgIterable<any>' type

I'm currently working with this simplistic component: import { Component, VERSION } from '@angular/core'; import { Observable, Observer } from 'rxjs'; @Component({ selector: 'my-app', templateUrl: './app.compone ...

In AngularJS, be sure to remove any previous growls before displaying a new one

Working on growl.info() using angularjs and have a query. How can I check if there is already a growl displayed on the screen before adding a new one? The requirement is that when a new growl is triggered, the previous one should be removed from the view. ...

Is it possible to retrieve the distinct errors detected by ESLint?

I'm currently in the process of refactoring a project using TypeScript and React. After adding ESLint, I found over 300 errors scattered throughout the codebase. Facing such a significant number of errors, it's clear that these can't all be ...

Photoshop JavaScript Character Identifier

It seems that the charIDToTypeID function is converting strings into IDs that Photoshop can use, but I'm encountering some IDs like "Lyr", "Ordn", and "Trgt" that I can't find any information on: var idLyr = charIDToTypeID( "Lyr " ); var idOrd ...