Skip to main content
agregue el código para mayor entendimiento y perdurabilidad de la información
Origen Enlace

Estructura de carpetas

>agenda
 >node_modules
 >src
   >app
    >app
      contacto.service.ts
     app.component.html
     app.component.spec.ts
     app.component.ts
     app.module.ts
     contacto.spec.ts
     contacto.ts
   index.html 
>API 
 .htacess
 .htaccess
 conexion.php
 config.php
 store.php

solo dejado los archivos que modifique ///agenda/src/index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Agenda</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
  <app-root></app-root>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

agenda/src/app/contactos.ts

export class Contacto {
    constructor(
        id: number,
        name: string,
        age: number,
        cellphone: string){}

}

agenda/src/app/app/contacto.service.ts

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

import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Contacto } from '../contacto';


@Injectable({
  providedIn: 'root'
})
export class ContactoService {
  baseUrl = 'http://localhost/api';

  constructor(private http: HttpClient) { }

  Contactos: Contacto[];

  getAll(): Observable<Contacto[]> {
    return this.http.get(`${this.baseUrl}/list`).pipe(
      map((res) => {
        this.Contactos = res['data'];
        return this.Contactos;
    }),
    
    catchError(this.handleError));
  }
  private handleError(error: HttpErrorResponse) {
    console.log(error);
   
    // return an observable with a user friendly message
    return throwError('Error! something went wrong.');
  }
  store(contacto: Contacto): Observable<Contacto[]> {
    return this.http.post(`${this.baseUrl}/store`, { data: Contacto })
      .pipe(map((res) => {
        this.Contactos.push(res['data']);
        return this.Contactos;
      }),
      catchError(this.handleError));
}
update(car: Contacto): Observable<Contacto[]> {
  return this.http.put(`${this.baseUrl}/update`, { data: car })
    .pipe(map((res) => {
      const theCar = this.Contactos.find((item) => {
        return +item['id'] === +car['id'];
      });
      if (theCar) {
        theCar['price'] = +car['price'];
        theCar['model'] = car['model'];
      }
      return this.Contactos;
    }),
    catchError(this.handleError));
}
}

agenda/src/app/app.component.html

<!--nav-->
<app-nav></app-nav>
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<!--table-->
<app-table></app-table>
<!--modal-->
<app-addmodal></app-addmodal>
<!--from index pp-->
<div id="theForm">
  <h2>The form</h2>
  <form #f="ngForm" name="theForm" (submit)="addcontaco(f)">
    <!--name-->
    <div class="form-group">
      <label>Name</label>
      <input type="text" class="form-control" name="name" [(ngModel)]="contacto.name" #contaconame="ngModel" required pattern="^[a-zA-Z]+$">
  <!--<span class="help-block danger" *ngIf="contacoModel.errors?.required && contacoModel.touched">
        The name is required
      </span>    
      <span class="help-block danger" *ngIf="contacoModel.errors?.pattern && contacoModel.touched">
        The model name can only contain the letters a-z or A-Z
      </span>-->
    </div>
    <!--age-->
    <div class="form-group">
      <label>Age</label>
      <input type="number" class="form-control" name="age" required [(ngModel)]="contaco.age" #contacoAge="ngModel">
      <!-- <span class="help-block danger" *ngIf="contacoAge.errors?.required && contacoAge.touched">
        The price is required
      </span>-->
    </div>
    <!--cell phone-->
    <div class="form-group">
        <label>Cell phones</label>
        <input type="number" class="form-control" name="age" required [(ngModel)]="contaco.cellphone" #contacoCellphone="ngModel">
       <!-- <span class="help-block danger" *ngIf="contacoCellphone.errors?.required && contacoCellphone.touched">
          The price is required
        </span>-->
      </div>
    <button
        class="btn btn-primary btn-sm"
        [disabled]="f.invalid">Add</button>
  </form>
  <!--table cont-->
  <div id="theList">
      <h2>The list</h2>
    
      <div class="list-group">
        <div *ngFor="let item of cars;let i = index;" class="list-group-item row">
          <div class="col-md-4">
            <input type="text"
                   [(ngModel)]="contacto[i].model"
                   class="form-control"
                   required
                   pattern="^[a-zA-Z]+$"
                   #model="ngModel"
                   [ngClass]="{ 'is-invalid': model.touched && model.invalid }">
          </div>
          <div class="col-md-4">
            <input type="number"
                   [(ngModel)]="cars[i].price"
                   class="form-control"
                   required
                   #price="ngModel"
                   [ngClass]="{ 'is-invalid': price.touched && price.invalid }">
          </div>
          <div class="col-md-4">
            <input type="button"
                   value="Update"
                   class="btn btn-success btn-sm"
                   [disabled]="model.invalid || price.invalid"
                   (click)="updateCar(model, price, item.id)">
          </div>
        </div>
      </div>
    </div>
</div>

agenda/src/app/app.component.spec.ts

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });

  it(`should have as title 'agenda'`, () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('agenda');
  });

  it('should render title in a h1 tag', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('Welcome to agenda!');
  });
});

agenda/src/app/app.component.ts

import { Component, OnInit } from '@angular/core';

import { Contacto } from './contacto';
import { ContactoService } from './app/contacto.service';

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

export class AppComponent implements OnInit{
  Contactos: Contacto[];
  error='';
  success='';
  title = 'agenda';
  constructor(private ContactoService:ContactoService){}
  ngOnInit() {
    this.geContactos();
  }
        
  geContactos(): void {
    this.ContactoService.getAll().subscribe(
      (res: Contacto[]) => {
        this.Contactos = res;
      },
      (err) => {
        this.error = err;
      }
    );
  }
  contacto = new Contacto(0,'',0,'');
  addContactos(f) {
    this.error = '';
    this.success = '';

    this.ContactoService.store(this.Contactos)
      .subscribe(
        (res: Contacto[]) => {
          // Update the list of contacts
          this.Contactos = res;

          // Inform the user
          this.success = 'Created successfully';

          // Reset the form
          f.reset();
        },
        (err) => this.error = err
      );
}
updateContactos(id, name, age, cellphone) {
  this.success = '';
  this.error = '';

  this.ContactoService.update({ id:id.value, contacto:  name.value, age: age.value, cellphone: cellphone.value })
    .subscribe(
      (res) => {
        this.contacto    = res;
        this.success = 'Updated successfully';
      },
      (err) => this.error = err
    );
}
}

agenda/src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { NavComponent } from './nav/nav.component';
import { TableComponent } from './table/table.component';
import { AddmodalComponent } from './addmodal/addmodal.component';

@NgModule({
  declarations: [
    AppComponent,
    NavComponent,
    TableComponent,
    AddmodalComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

agenda/src/app/contacto.spec.ts

import { Contacto } from './contacto';

describe('Contacto', () => {
  it('should create an instance', () => {
    expect(new Contacto()).toBeTruthy();
  });
});

API/.htacess

export class Contacto {
    constructor(
        id: number,
        name: string,
        age: number,
        cellphone: string){}

}

API/.htaccess

# Remove the php extension from the filename
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

# Set the headers for the restful api
Header always set Access-Control-Allow-Origin http://localhost:4200
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"

API/conexion.php

<?php
//call config.php
require_once 'config.php';

$dsn = "pgsql:host=$host;
port=$port;
dbname=$db;
user=$username;
password=$pass";

try {
    //create conexion with postgres
    $conn = new PDO($dsn);
    echo "conectado";

} catch (PDOException $e) {
    //error de conexion string
     $e->getMessage();
     $tmp = "Error de conexion.";
    
     //error conexion 
     pg_dump($tmp);
    
} 
?>

API/config.php

<?php
// insert data of conexion 
$host='localhost';
$db='agenda';
$username='polo';
$pass="adc12345";
$port="5432";
?>

API/store.php

<?php
require 'conexion.php';

// Get the posted data.
$postdata = file_get_contents("php://input");

if(isset($postdata) && !empty($postdata))
{
  // Extract the data.
  $request = json_decode($postdata);
    

  // Validate.
  if(trim($request->data->name) === '')
  {
    return http_response_code(400);
  }
    
  // Sanitize.
  //$model = mysqli_real_escape_string($con, trim($request->data->model));
  //$name = $con,trim($request->data->name);  
  //$price = mysqli_real_escape_string($con, (int)$request->data->price);

  // Store.
  $sql = "INSERT INTO contacto (name,age,cell) VALUES ('{name}',{age},'{cellphone}')";
  $result = pg_query($conn,$sql);
  if($result = pg_query($conn,$sql))
  {
    http_response_code(201);
    $contacto = [
      'name' => $name,
      'age' => $age,
      'cellphone' => $cellphone
    ];
    echo json_encode(['data'=>$contacto]);
  } else {
    http_response_code(422);
  }
}

Estructura de carpetas

>agenda
 >node_modules
 >src
   >app
    >app
      contacto.service.ts
     app.component.html
     app.component.spec.ts
     app.component.ts
     app.module.ts
     contacto.spec.ts
     contacto.ts
   index.html 
>API 
 .htacess
 .htaccess
 conexion.php
 config.php
 store.php

solo dejado los archivos que modifique ///agenda/src/index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Agenda</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
  <app-root></app-root>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

agenda/src/app/contactos.ts

export class Contacto {
    constructor(
        id: number,
        name: string,
        age: number,
        cellphone: string){}

}

agenda/src/app/app/contacto.service.ts

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

import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Contacto } from '../contacto';


@Injectable({
  providedIn: 'root'
})
export class ContactoService {
  baseUrl = 'http://localhost/api';

  constructor(private http: HttpClient) { }

  Contactos: Contacto[];

  getAll(): Observable<Contacto[]> {
    return this.http.get(`${this.baseUrl}/list`).pipe(
      map((res) => {
        this.Contactos = res['data'];
        return this.Contactos;
    }),
    
    catchError(this.handleError));
  }
  private handleError(error: HttpErrorResponse) {
    console.log(error);
   
    // return an observable with a user friendly message
    return throwError('Error! something went wrong.');
  }
  store(contacto: Contacto): Observable<Contacto[]> {
    return this.http.post(`${this.baseUrl}/store`, { data: Contacto })
      .pipe(map((res) => {
        this.Contactos.push(res['data']);
        return this.Contactos;
      }),
      catchError(this.handleError));
}
update(car: Contacto): Observable<Contacto[]> {
  return this.http.put(`${this.baseUrl}/update`, { data: car })
    .pipe(map((res) => {
      const theCar = this.Contactos.find((item) => {
        return +item['id'] === +car['id'];
      });
      if (theCar) {
        theCar['price'] = +car['price'];
        theCar['model'] = car['model'];
      }
      return this.Contactos;
    }),
    catchError(this.handleError));
}
}

agenda/src/app/app.component.html

<!--nav-->
<app-nav></app-nav>
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<!--table-->
<app-table></app-table>
<!--modal-->
<app-addmodal></app-addmodal>
<!--from index pp-->
<div id="theForm">
  <h2>The form</h2>
  <form #f="ngForm" name="theForm" (submit)="addcontaco(f)">
    <!--name-->
    <div class="form-group">
      <label>Name</label>
      <input type="text" class="form-control" name="name" [(ngModel)]="contacto.name" #contaconame="ngModel" required pattern="^[a-zA-Z]+$">
  <!--<span class="help-block danger" *ngIf="contacoModel.errors?.required && contacoModel.touched">
        The name is required
      </span>    
      <span class="help-block danger" *ngIf="contacoModel.errors?.pattern && contacoModel.touched">
        The model name can only contain the letters a-z or A-Z
      </span>-->
    </div>
    <!--age-->
    <div class="form-group">
      <label>Age</label>
      <input type="number" class="form-control" name="age" required [(ngModel)]="contaco.age" #contacoAge="ngModel">
      <!-- <span class="help-block danger" *ngIf="contacoAge.errors?.required && contacoAge.touched">
        The price is required
      </span>-->
    </div>
    <!--cell phone-->
    <div class="form-group">
        <label>Cell phones</label>
        <input type="number" class="form-control" name="age" required [(ngModel)]="contaco.cellphone" #contacoCellphone="ngModel">
       <!-- <span class="help-block danger" *ngIf="contacoCellphone.errors?.required && contacoCellphone.touched">
          The price is required
        </span>-->
      </div>
    <button
        class="btn btn-primary btn-sm"
        [disabled]="f.invalid">Add</button>
  </form>
  <!--table cont-->
  <div id="theList">
      <h2>The list</h2>
    
      <div class="list-group">
        <div *ngFor="let item of cars;let i = index;" class="list-group-item row">
          <div class="col-md-4">
            <input type="text"
                   [(ngModel)]="contacto[i].model"
                   class="form-control"
                   required
                   pattern="^[a-zA-Z]+$"
                   #model="ngModel"
                   [ngClass]="{ 'is-invalid': model.touched && model.invalid }">
          </div>
          <div class="col-md-4">
            <input type="number"
                   [(ngModel)]="cars[i].price"
                   class="form-control"
                   required
                   #price="ngModel"
                   [ngClass]="{ 'is-invalid': price.touched && price.invalid }">
          </div>
          <div class="col-md-4">
            <input type="button"
                   value="Update"
                   class="btn btn-success btn-sm"
                   [disabled]="model.invalid || price.invalid"
                   (click)="updateCar(model, price, item.id)">
          </div>
        </div>
      </div>
    </div>
</div>

agenda/src/app/app.component.spec.ts

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });

  it(`should have as title 'agenda'`, () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('agenda');
  });

  it('should render title in a h1 tag', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('Welcome to agenda!');
  });
});

agenda/src/app/app.component.ts

import { Component, OnInit } from '@angular/core';

import { Contacto } from './contacto';
import { ContactoService } from './app/contacto.service';

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

export class AppComponent implements OnInit{
  Contactos: Contacto[];
  error='';
  success='';
  title = 'agenda';
  constructor(private ContactoService:ContactoService){}
  ngOnInit() {
    this.geContactos();
  }
        
  geContactos(): void {
    this.ContactoService.getAll().subscribe(
      (res: Contacto[]) => {
        this.Contactos = res;
      },
      (err) => {
        this.error = err;
      }
    );
  }
  contacto = new Contacto(0,'',0,'');
  addContactos(f) {
    this.error = '';
    this.success = '';

    this.ContactoService.store(this.Contactos)
      .subscribe(
        (res: Contacto[]) => {
          // Update the list of contacts
          this.Contactos = res;

          // Inform the user
          this.success = 'Created successfully';

          // Reset the form
          f.reset();
        },
        (err) => this.error = err
      );
}
updateContactos(id, name, age, cellphone) {
  this.success = '';
  this.error = '';

  this.ContactoService.update({ id:id.value, contacto:  name.value, age: age.value, cellphone: cellphone.value })
    .subscribe(
      (res) => {
        this.contacto    = res;
        this.success = 'Updated successfully';
      },
      (err) => this.error = err
    );
}
}

agenda/src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { NavComponent } from './nav/nav.component';
import { TableComponent } from './table/table.component';
import { AddmodalComponent } from './addmodal/addmodal.component';

@NgModule({
  declarations: [
    AppComponent,
    NavComponent,
    TableComponent,
    AddmodalComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

agenda/src/app/contacto.spec.ts

import { Contacto } from './contacto';

describe('Contacto', () => {
  it('should create an instance', () => {
    expect(new Contacto()).toBeTruthy();
  });
});

API/.htacess

export class Contacto {
    constructor(
        id: number,
        name: string,
        age: number,
        cellphone: string){}

}

API/.htaccess

# Remove the php extension from the filename
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

# Set the headers for the restful api
Header always set Access-Control-Allow-Origin http://localhost:4200
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"

API/conexion.php

<?php
//call config.php
require_once 'config.php';

$dsn = "pgsql:host=$host;
port=$port;
dbname=$db;
user=$username;
password=$pass";

try {
    //create conexion with postgres
    $conn = new PDO($dsn);
    echo "conectado";

} catch (PDOException $e) {
    //error de conexion string
     $e->getMessage();
     $tmp = "Error de conexion.";
    
     //error conexion 
     pg_dump($tmp);
    
} 
?>

API/config.php

<?php
// insert data of conexion 
$host='localhost';
$db='agenda';
$username='polo';
$pass="adc12345";
$port="5432";
?>

API/store.php

<?php
require 'conexion.php';

// Get the posted data.
$postdata = file_get_contents("php://input");

if(isset($postdata) && !empty($postdata))
{
  // Extract the data.
  $request = json_decode($postdata);
    

  // Validate.
  if(trim($request->data->name) === '')
  {
    return http_response_code(400);
  }
    
  // Sanitize.
  //$model = mysqli_real_escape_string($con, trim($request->data->model));
  //$name = $con,trim($request->data->name);  
  //$price = mysqli_real_escape_string($con, (int)$request->data->price);

  // Store.
  $sql = "INSERT INTO contacto (name,age,cell) VALUES ('{name}',{age},'{cellphone}')";
  $result = pg_query($conn,$sql);
  if($result = pg_query($conn,$sql))
  {
    http_response_code(201);
    $contacto = [
      'name' => $name,
      'age' => $age,
      'cellphone' => $cellphone
    ];
    echo json_encode(['data'=>$contacto]);
  } else {
    http_response_code(422);
  }
}
Origen Enlace

No logro comunicar bien php con angular

hola necesito ayuda estoy tratando de aprender angular y este es mi primer proyecto angular. Estoy usando angular 7.2 y php7.2 e generado una API para poder conectar a php con angular pero al parecer no se están comunicando bien porque no me actualizan los datos en la base de datos la cual estoy usando postgresql-10.9 dejo el enlace a mi código esta alojado en github ayuda :)

https://github.com/rafa2022/Mytest/tree/master/pp5/proyect