How to pass new data from one page to another page when using Angular HttpClient and InMemoryDbService?

I tried adding a new position on the "Positions" page,enter image description here

and it appeared in the position list.enter image description here

But, I am not sure how to make the new position appear in the dropdown list on the "Employees" page.enter image description here

Here's what I've done so far.

in-memory-data-service.ts

...

export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    const employees = [
      { id: 'abc1', name: 'abc', position: 'Manager'},
      { id: 'abc2', name: 'def', position: 'Manager'},
      { id: 'abc3', name: 'ghi', position: 'Developer'},
      { id: 'abc4', name: 'jkl', position: 'Consultant'},
      { id: 'abc5', name: 'mno', position: 'Developer'},
      { id: 'abc6', name: 'pqr', position: 'IT Intern'}
    ];
    const positions = [
      { position: 'Manager'},
      { position: 'Developer'},
      { position: 'Consultant'},
      { position: 'IT Intern'}
    ];
    return {employees, positions};
  }
  constructor() { }
}

employeePosition.services.ts

...
export class employeePositionService {

  private positionsUrl = 'api/positions';

  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };

  constructor(private http: HttpClient) { }

  getEmployeePositions(): Observable<employeePosition[]> {
    return this.http.get<employeePosition[]>(this.positionsUrl).pipe(
      tap(_ => this.log('fetched positions')),
      catchError(this.handleError<employeePosition[]>('getEmployeePositions', []))
    );
  }

  addEmployeePosition(position: employeePosition): Observable<employeePosition> {
    return this.http.post<employeePosition>(this.positionsUrl, position, this.httpOptions).pipe(
      tap((newPosition: employeePosition) => this.log(`added position with id=${newPosition}`)),
      catchError(this.handleError<employeePosition>('addEmployeePosition'))
    );
  }
...

positions.component.html

...
<tr *ngFor="let employeePosition of employeePositions; let i = index" scope="row">
        <td class="text-center">
          
        </td>
        <td class="text-center">
          <button mdbRipple type="button" class="btn btn-primary btn-sm" 
             (click)="editPosition(employeePosition, i)" >Edit</button>&nbsp;
          <button mdbRipple type="button" class="btn btn-primary btn-sm" 
             (click)="deletePosition(employeePosition, i, employeePositions)" >Delete</button>
        </td>
      </tr>
...

positions.component.ts

...
employeePosition: employeePosition | undefined;
employeePositions: employeePosition[] = [];
...
getEmployeePositions(): void {
  this.employeePositionService.getEmployeePositions()
   .subscribe(employeePositions => this.employeePositions = employeePositions);
}

addPosition(size: string = ''): void {
  this.modalRefAdd = this.modalService.open(AddPositionFormComponent, {
    modalClass: size,
    data: {}
  });

  this.modalRefAdd.onClose.subscribe(res => {
    if(res != null) {
      this.employeePositions = [...this.employeePositions, res];
    } else {
      close();
    }
  });
}

add-position-form.component.ts

...
onSubmit() {
    this.positionForm.markAllAsTouched();
    if(this.positionForm.invalid) {
      return
    } else {
      const data = this.positionForm.value;
      console.log(data);
      console.log(data.position);
      this.employeePositionService.addEmployeePosition({position: data.position} as 
      employeePosition).subscribe(result => {
        this.employeePositionService.getEmployeePositions().subscribe(results => console.log(results))
      });

      this.modalRefAdd.close(data);
    }
  }
...

add-user-form.component.html

<div id="add-employee-position">
  <div class="modal-header evonik white-text">
      <h5 class="modal-title text-white">Create New Position</h5>
      <button type="button" class="close pull-right" aria-label="Close" (click)="modalRefAdd.close()"><span aria-hidden="true" style="color: #000000;">×</span></button>
  </div>

  <div class="modal-body m-0 p-50">
      <form [formGroup]="positionForm" (ngSubmit)="onSubmit()">
          <div class="form-group pb-1">
              <label>Position:</label>
          </div>
          <div class="class form-row pb-3">
              <div class="class col">
                  <mdb-form-control>
                      <input mdbValidate mdbInput type="text" formControlName="position" class="form-control" required>
                      <label mdbLabel class="form-label">Enter a new position here</label>
                      <mdb-error *ngIf="position?.invalid && (position?.dirty || position?.touched)">New position is required</mdb-error>
                  </mdb-form-control>
              </div>
          </div>
      </form>
  </div>
  <div class="modal-footer mt-1">
      <button mdbRipple type="button" class="btn btn-outline-primary" (click)="modalRefAdd.close()">Cancel</button>
      <button mdbRipple type="button" class="btn btn-primary" (click)="onSubmit()">Confirm</button>
  </div>

add-user-form.component.ts

...
employeePositions: employeePosition[] = [];
...
get id(): AbstractControl {
    return this.userForm.get('id')!;
   }

   get name(): AbstractControl {
    return this.userForm.get('name')!;
   }

   get position(): AbstractControl {
    return this.userForm.get('position')!;
   }

  ngOnInit(): void {    
    this.getEmployeePositions();
  }

  getEmployeePositions(): void {
    this.employeePositionService.getEmployeePositions()
      .subscribe(employeePositions => this.employeePositions = employeePositions);
  }

  onSubmit() {
    this.userForm.markAllAsTouched();
    if(this.userForm.invalid) {
      return
    } else {
      const data = this.userForm.value;
      console.log(data);
      console.log(data.id);
      this.employeeService.addEmployee({id : data.id, name: data.name, position: data.position} as Employee).subscribe(result => {
        this.employeeService.getEmployees().subscribe(results => console.log(results))
      });
  
      this.modalRefAdd.close(data);
    }
  }
...

I hope someone can assist me with this problem. Thank you in advance.



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations