Get by Id not working in angular 4 how to get the data into a form

时间:2018-04-18 17:58:40

标签: javascript angular

I want to navigate to my edit page which is -EditTruckComponent from another component TruckComponent , so I using router link in the truckComponent like this

  <tr *ngFor="let truck of trucks | async">
              <td>{{truck.truckId}}</td> 
              <td>{{truck.truckCode}}</td>
              </a>
              <td>{{truck.purchasedDate | date: 'yyyy-MM-dd'}}</td>
              <td>{{truck.descriptions}}</td>
              <td class="text-right">
                <a class="btn-sm btn-outline-secondary"
                   ngbTooltip="Edit Truck"
                   placement="top">
                  <i class="fa fa-bus"></i> <span
                  class="d-none d-md-inline" [routerLink]="['/editsTrucks', truck.truckId]">Edit</span></a>

And to receive a truckBy id i am doing this in my EditTruckComponent

  @Input() truck: Truck;
  processValidation = false;
  statusCode: number;
  requestProcessing = false;

  truckForm = new FormGroup({
    truckCode: new FormControl('', Validators.required),
    date: new FormControl('', Validators.required),
    descriptions: new FormControl('', Validators.required)
  });

  constructor(private truckService: TruckService,
              private router: Router, private route: ActivatedRoute) {
  }

  ngOnInit(): void {
    this.route.params
      .switchMap((params: Params) => this.truckService.getTruckById(+params['truckId']))
      .subscribe(truck => this.truck = truck);
  }

here i am using @Input tp indicate the recieving entity and router params for the id

but I am un able to populate my editTruck html with the data , it says truck id is undefined so I tried using truck?.truckId then it refuses to show the form completely below is my html and console output

ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 18, nodeDef: {…}, elDef: {…}, elView: {…}}
View_EditTruckComponent_0 @ EditTruckComponent.html:15
proxyClass @ compiler.js:14653
DebugContext_.logError @ core.js:14996
ErrorHandler.handleError @ core.js 
ZoneTask.invokeTask @ zone.js:500
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
truck.service.ts:87 Http failure response for http://localhost:8088/trucks/2: 302 Found
TruckService.handleError @ truck.service.ts:87

And my edit truck html

header>
  <nav id="main-header"
       class="py-1 mb-3 navbar navbar-expand-sm navbar-light bg-light text-dark">
    <span class="navbar-brand text-uppercase mr-auto">
      <a class="btn alert-secondary" (click)="back()" role="button">Back</a></span>
    <ul class="navbar-nav">
      <li class="nav-item">
        <a type="submit" form="editFormTruck"
           (click)="processForm()"

           class="btn btn-light"
           title="Save Truck"
           data-toggle="tooltip"
           data-placement="bottom">
          <i class="fa fa-save"></i> <span class="d-none d-sm-inline"   *ngIf="truck.truckId === null">Save</span>
          <span class="d-none d-sm-inline" *ngIf="truck.truckId">Update</span>
        </a></li>
    </ul>
  </nav>
</header>

<section id="department">
  <div class="container-fluid">
    <div class="row">
      <div class="col">
        <div class="card">
          <div class="card-body">
            <form [formGroup]="truckForm" (ngSubmit)="processForm()"   id="editFormTruck"  >

              <!--truck code-->
              <div class="form-group">
                <label class="form-control-label" *ngIf="truckForm.get('truckCode').invalid && processValidation"
                       required="required" [ngClass]="'error'"
                       for="truckCode">truck code is required.</label>
                <input formControlName="truckCode"
                       id="truckCode"
                       class="form-control"
                       type="text"
                       name="truckCode"
                       required
                       [(ngModel)]="truck.truckCode"/> Truck Code
                <div *ngIf="statusCode === 409" [ngClass]="'success'">
                  Truck with such Code already exists try another TruckCode.
                </div>
              </div>
            <div>

I also tried this on my truckComponent

    <app-edit-truck [truck]="truck$ | async"></app-edit-truck>

    export class EditTruckParentComponent {
        truck$: Observable < Truck > ;

        constructor(private truckService: TruckService) {
            this.truck$ = this.truckService.getTruckById(truckId);
        }
    }

but my app.component.html 
has this so could not add async to the page

 <app-navigation></app-navigation>
<router-outlet (activate)='onActivate($event)'
               (deactivate)='onDeactivate($event)'></router-outlet>

This is how my service looks like

  private baseUrl: string = 'http://localhost:8088/trucks';
  getTruckById(id: number): Observable<Truck> {
    return this.http.get(this.baseUrl + "/" + id)
      .pipe(map(this.extractData),
        catchError(this.handleError));
  }

1 个答案:

答案 0 :(得分:0)

看起来,您没有调用实际端点。您的错误显示为Http failure response for http://localhost:8088/trucks/2。我不明白这一点,看起来你正在用前端应用程序本身的URL做一个HTTP请求,要么让你的服务调用一个模拟数据,in-memory-web-api或一个实际的API。

请在订阅服务方法中执行此操作:

subscribe({
    (truck) => {
        this.truck = truck;
        console.log(truck);  // please tell what does it print?
    }
})

当你试图获得参数时,你可以这样做吗?虽然我不确定。

this.route.params.subscribe((params) => {
    this.truckService.getTruckById(+params['truckId'])
        .subscribe(
            (truck) => {
                this.truck = truck;
                console.log(truck);  // Subscribe to the service not the route.
            }
        )
})
相关问题