Как получить значения для конкретного идентификатора в Angular Using API (CRUD в Angular Using API) - PullRequest
0 голосов
/ 27 декабря 2018

Я выполняю CRUD In Angular, используя API в Laravel.Я добавил значения и получил значения, но я не могу обновить значения с помощью Id.

Это мой app.component.ts :

import {Component } from '@angular/core';
import {HttpClient, HttpHeaders } from '@angular/common/http';
import {Employee} from './employees';
import {EditComponent} from './edit/edit.component';
import {AppService} from './app.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [AppService]
})
export class AppComponent {
    form:any = {}
    msg: string = null;
    employees: Employee[];
    constructor( public http: HttpClient,private appService:AppService,private router: Router)
    {}

    onSubmit(){ 
      const httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' })
      };
      this.http.post('http://127.0.0.1:8000/api/employee',this.form,httpOptions)
      .subscribe(function(s){console.log('sss',s);},function(e){console.log('e',e);});
    }

    ngOnInit() {
    }

    getEmployee():void{
       this.appService.getEmployees().subscribe(employees=>(this.employees = employees))
     }
    }

    public editComponent: boolean = false;
    loadMyChildComponent($id) {
      this.editComponent = true;
      this.appService.setCurrentId($id);
    }
 }

В loadMyChildComponent ($ id) я получаю идентификатор строки для редактирования.

Это мой app.service.ts :

import {Injectable } from '@angular/core';
import {HttpClient,HttpParams} from '@angular/common/http';
import {HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs';
import {Employee} from './employees';
import {EditComponent } from './edit/edit.component';

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

@Injectable({
  providedIn: 'root'
})
export class AppService {
  employee: Employee[];
  id: number;
  private url = 'http://localhost:8000/api/employee/';
  constructor(private http: HttpClient) { }

  setCurrentId(id){
    this.id=id;
  }
  getCurrentId(){
   return  this.id;
  }

   getEmployees(): Observable<Employee[]>{
    return this.http.get<Employee[]>(`http://localhost:8000/api/employees`); 
   }

   editEmployees(id): Observable<{}>
   {
   const url2 = `http://localhost:8000/api/employee/${id}`;
   return this.http.get<Employee[]>(url2);
   }

  updateEmployees(employee: Employee): Observable<any> {
  return this.http.put(this.url, employee, httpOptions);
  }

}

В этом app.service.ts я получаю значения для определенного идентификатора, используя editEmployees (id).

Это мой edit.component.ts :

import {Component, OnInit, Input } from '@angular/core';
import {AppService } from '../app.service';
import {Employee } from '../employees';
import {Router } from '@angular/router'; 
import {HttpClient, HttpHeaders } from '@angular/common/http';
import {NgForm} from '@angular/forms';
import {Observable} from 'rxjs';
import {ActivatedRoute} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
  @Input() employee: Employee;
  form:any = {}

  constructor(public http: HttpClient,private appService:AppService,private router: Router,private route: ActivatedRoute) { }

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

  editEmployees(): void {
    const id =  this.appService.getCurrentId();
    this.appService.editEmployees(id).subscribe(employee => employee);
     console.log(id);
     console.log(employee);
  }

  onformSubmit():void{ 
    this.appService.updateEmployees(this.form.id)
     .subscribe(employee => employee = employee);
}
}

Когда я печатаю значения в консоли с помощью функции editEmployees (), она показываетне определено.

Это мои employee.ts :

export interface Employee{
    id: number;
    username:string;
    email:string;
    mobile:string;
    password:string;
}

Это мои app.component.html :

<table class="table"> 
  <tr>
  <th>Id</th>
  <th>User Name</th>
  <th>Email</th>
  <th>Mobile</th>
  <th>Edit</th>
  <th>Delete</th>
  </tr>
  <tr *ngFor="let employee of employees">
    <td>{{employee.id}}</td>
    <td>{{employee.username}}</td>
    <td>{{employee.email}}</td>
    <td>{{employee.mobile}}</td>
    <td><button (click)="loadMyChildComponent(employee.id);" class="btn btn-primary" [routerLink]="['/edit',employee.id]">Edit</button></td>
    <td><button class="btn btn-danger" (click)="delete(employee)" > Delete</button></td>
</table>

Поток таков: когда я нажимаю кнопку редактирования в app.component.html, он берет идентификатор и переходит в app.component.ts.Из app.component.ts он перейдет в app.service.ts, где будет извлекать значения из API с использованием определенного идентификатора.Из app.service.ts он передает значения в edit.component.ts и, используя edit.component.ts, передает значения в edit.component.html.

Но проблема в том, что в edit.component.ts он показывает undefined в функции editEmployees ().Любая помощь очень ценится.

1 Ответ

0 голосов
/ 27 декабря 2018

Измените следующее:

this.appService.editEmployees(id).subscribe(employee => employee);
 console.log(id);
 console.log(employee);

на

this.appService.editEmployees(id).subscribe(employees => {
   this.employee = employees[0];
   console.log(id);
   console.log(employee);
});

в вашем edit.component файле

...