Home > Net >  Angular :: ERROR TypeError: Cannot convert undefined or null to object
Angular :: ERROR TypeError: Cannot convert undefined or null to object

Time:06-07

I am using Spring Boot as backend and Angular as FrontEnd. I am sending a GET request from Angular to fetch Location City from Backend database and save it in variable to populate a drop-down. I have used a button to send the request, while pressing the button for the first time I am getting a error as mentioned in above title, but if I press the button for second time I successfully get the data. I want to send the GET request and set the data in controller. Please help to solve the error so that I can fetch the data in 1st time.

Angular version: 13.3.7  
Typescipt version: 4.6.4
Please check my below code:
home.component.html

Currently, I have hardcoded the value in drop-down

<section >
    <div >
      <div >
        <div >
          <div
            
            style="border-radius: 15px"
          >
            <div >
              <h1 >Booking Form</h1>
              <hr>
              <form (ngSubmit)="getBookingFormData()">
                <div >
                  <div >
                    <label >From</label>
                    <select
                      
                      id="country"
                      [(ngModel)]="booking.from"
                      name="country"
                    >
                      <option *ngFor="let country of stringifiedData" [value]="country">
                        {{ country }}</option>
                    </select>
      
                  </div>
                  <div >
                    <div >
                      <label >To</label>
                      <select
                        
                        id="country"
                        [(ngModel)]="booking.to"
                        name="country"
                      >
                        <option value="1">Choose option</option>
                        <option value="Mumbai">Mumbai</option>
                        <option value="Delhi">Delhi</option>
                        <option value="Kolkata">Kolkata</option>
                      </select>
                    </div>
                </div>
                <div >
                    <div >
                        <label id="example-radio-group-label">Birth date: </label>
                        <div  data-provide="datepicker">
                          <input type="date"  
                          [(ngModel)]="booking.date"
                          name="birthdayDate"
                          />
                          <div >
                            <span ></span>
                          </div>
                        </div>
                      </div>
                </div>
  
                <div >
                  <button type="submit" mat-raised-button color="primary">
                    Book Now!</button>
                </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
</section>  
{{booking | json}}

home.component.ts

import { Component, OnInit } from '@angular/core';
import { LocationService } from 'src/app/service/location.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  //Variables to be used in the html file
  stringifiedData: any[] = ["Mumbai", "Surat"];
  Location: any;
  booking = {
    from !: "",
    to !: "",
    date !: ""
  }

  fetchLocation()
  {
    this.GetRequest.fetchLocation().subscribe(data => this.Location = data)
    for (let i = 0; i < Object.keys(this.Location).length; i  )
    {
      this.stringifiedData.push(this.Location[i].locationName);
    }
    console.log(this.stringifiedData);
  }
  getBookingFormData()
  {
    if(!(this.validateForm()))
    {
      this.fetchLocation();
    }
  }
  validateForm()
  {
    if (this.booking.from == "" || this.booking.to == "" || this.booking.date == "")
    {
      alert("Please fill in all the fields");
      return false;
    }
    else if (this.booking.from == this.booking.to)
    {
      alert("Please select different destinations");
      return false;
    }
    else if (this.booking.date < new Date().toISOString().split('T')[0])
    {
      alert("Please select a future date");
      return false;
    }
    else 
    {
      console.log(this.booking);
      return true;
    }
  }

  constructor(private GetRequest : LocationService) { 
    try {
      //this.fetchLocation();
    } catch (error) {
      console.log("Error");
    }
  }

  ngOnInit(): void {

  }

}

location.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class LocationService {
  private baseUrl:string = "http://localhost:8080";
  constructor(private http:HttpClient) {
  }

  fetchLocation()
  {

      return this.http.get<Location[]>(`${this.baseUrl}/getLocations`);  
  }
}

Backend:

LocationController.java

package com.example.democom.travelbuddy.controller;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.democom.travelbuddy.entities.LocationDO;
import com.example.democom.travelbuddy.helper.LocationService;

@RestController
@CrossOrigin
public class LocationController {
    @Autowired
    private LocationService locationService;


    @GetMapping("/getLocations")
    public ResponseEntity fetchLocation()
    {
        System.out.println("In LocationController");
        List<LocationDO> locationDO = locationService.getLocation();
        if (locationDO.size() > 0)
        {
            return ResponseEntity.of(Optional.of(locationDO));
        }
        else
        //To return custome HTTPResponse
        return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    }
    
}

LocationDO.java

package com.example.democom.travelbuddy.entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class LocationDO {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "locationseq")
    private Long locationId;
    @Column(name = "locationname")
    private String locationName;
    public Long getLocationId() {
        return locationId;
    }
    public void setLocationId(Long locationId) {
        this.locationId = locationId;
    }
    public String getLocationName() {
        return locationName;
    }
    public void setLocationName(String locationName) {
        this.locationName = locationName;
    }

    
}

LocationService.java

package com.example.democom.travelbuddy.helper;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.democom.travelbuddy.dao.LocationRepository;
import com.example.democom.travelbuddy.entities.LocationDO;

@Service
public class LocationService {
    @Autowired
    LocationRepository locationRepository;
    public List<LocationDO> getLocation() {
        List<LocationDO> locationDOs = new ArrayList<>();
        locationRepository.findAll().forEach(locationDOs::add);
        return locationDOs;
    }
}

LocationRepository.java

package com.example.democom.travelbuddy.dao;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;

import com.example.democom.travelbuddy.entities.LocationDO;

@Component
public interface LocationRepository extends CrudRepository<LocationDO , Long> {

}

Please check given link for error image that I got in console: enter image description here

CodePudding user response:

You have to push to this.stringifiedData in the subscribe as below.

  fetchLocation()
  {
    this.GetRequest.fetchLocation().subscribe(data => {
      this.Location = data;
      for (let i = 0; i < Object.keys(this.Location).length; i  )
      {
        this.stringifiedData.push(this.Location[i].locationName);
      }
      console.log(this.stringifiedData);
    });
  }
  • Related