0
votes

I am trying to build a basic angular phone book application with ability to view, create contacts. I have used the HTTPClient Post request to create contacts similar to the way demonstrated in Angular heroes tutorial but the post request is failing with following Error "HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/assets/contacts.json", ok: false, …}" the following is my service file

    import { HttpClient } from '@angular/common/http';
    import { Contact } from './contact';
    import { Observable } from 'rxjs';

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

      constructor(private httpClient: HttpClient) { }

      contactUrl = 'assets/contacts.json';

      getContacts(): Observable<Contact []> {
        return this.httpClient.get<Contact []>(this.contactUrl);
      }

      postContact(contact: Contact): Observable<Contact> {
        return this.httpClient.post<Contact>(this.contactUrl,contact);
      } 

    }

this one is component.ts

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, FormControl} from '@angular/forms';
import { Contact } from '../contact';
import { ContactInfoService } from '../contact-info.service';


@Component({
  selector: 'app-contact-model',
  templateUrl: './contact-model.component.html',
  styleUrls: ['./contact-model.component.css']
})
export class ContactModelComponent {
   contactForm: FormGroup;
  contacts: Contact[];

  constructor(
    private formBuilder: FormBuilder,
    private contactInfoService: ContactInfoService
  ) {
      this.contactForm = new FormGroup({
        firstName: new FormControl(''),
        lastName: new FormControl(''),
        eMail: new FormControl(''),
        phoneNumber: new FormControl(''),
        status: new FormControl('')
      });
   }



  postContact(): void {

    var newContact: Contact;
    newContact = {}; 
    newContact.firstName = this.contactForm.get('firstName').value;
    newContact.lastName = this.contactForm.get('lastName').value;
    newContact.email = this.contactForm.get('eMail').value;
    newContact.phoneNumber = this.contactForm.get('phoneNumber').value;
    newContact.status = this.contactForm.get('status').value;
    console.log(newContact);

    this.contactInfoService.postContact(newContact).subscribe(contact => this.contacts.push(contact));
  }

  getContacts(): void {
    this.contactInfoService.getContacts().subscribe(contacts => (this.contacts = contacts));
  }

}

this one is html file

<div class="jumbotron">
<h3>New Contact</h3>

<form [formGroup]= "contactForm">
    <div>
        <label for="firstName">
            First Name
        </label><br>
        <input id="firstName" type="text" formControlName="firstName">
    </div>

    <div>
        <label for="lastName">
            Last Name
        </label><br>
        <input id="lastName" type="text" formControlName="lastName">
    </div>

    <div>
        <label for="eMail">
            Email
        </label><br>
        <input id="eMail" type="email" formControlName="eMail">
    </div>

    <div>
        <label for="phoneNumber">
            Phone Number
        </label><br>
        <input id="phoneNumber" type="tel" formControlName="phoneNumber" pattern="[0-9]{10}">
    </div>

    <div>
        <label>
            Status
        </label><br>
        <input id="Active" type="radio" value="Active" formControlName="status">
        <label for="Active">Active</label><br>
        <input id="Inactive" type="radio" value="Inactive" formControlName="status">
        <label for="Inactive">Inactive</label><br>
    </div>


    <button type="submit" (click)="postContact(); getContacts()">Add</button>
</form>
</div>

this is json file

[
    { 
     "id": "1",
     "firstName":"abc",
     "lastName":"cba",
     "email":"[email protected]",
     "phoneNumber":"1234567890",
     "status":"active"
     },
     { 
        "id": "2",
        "firstName":"def",
        "lastName":"fed",
        "email":"[email protected]",
        "phoneNumber":"0987654321",
        "status":"inactive"
    }
 ]

When I click the Add button, in networks tab I see the post request with status 404. I have found several questions similar to this but none have worked for me. If you have any ideas how to fix this issue or experienced the similar problem - any help or comment will be highly appreciated.

Thank you

1
You need a webserver to handle the POST request. The dev server that comes with angular only serves files, it does not handle other requests - David
I have to fetch the data from a json file on my local does that require a web server too, if yes can you explain how I do that, I'm just a beginner - sai shashank Rayaprolu

1 Answers

2
votes

You are getting a 404 error which means a page not found error. Therefore there is a good chance that the endpoint you are referring from the angular app does not exist. Therefore please check the contactUrl again or just check the endpoint with postman and paste the URL and see if it works.