Angular 7 - Как отображать данные сразу после отправки - PullRequest
0 голосов
/ 14 октября 2019

В настоящее время я работаю над проектом, использующим Angular-7 в качестве внешнего интерфейса и Laravel-5.8 в качестве внутреннего. У меня есть запрос POST, как показано ниже:

ApiController.php

public function createClientQuote(Request $request) {
        $request->validate([
                    'first_name' => 'required',
                    'last_name' => 'required',
                    'email' => 'required|email',
                    'phone' => 'required|max:14',
                    'business_name' => 'string',
                    'truck_type' => 'required',
                    'truck_required' => 'required',
                    'quote_origin' => 'required',
                    'quote_destination' => 'required',
                    'commodity' => 'required',  
                    'loading_date' => 'date|required' 
        ]);
        $clientquote = new ClientQuote;
        $clientquote->first_name=$request->get('first_name');
        $clientquote->last_name=$request->get('last_name');
        $clientquote->email=$request->get('email');
        $clientquote->phone=$request->get('phone');
        $clientquote->business_name=$request->get('business_name');
        $clientquote->truck_type=$request->get('truck_type');
        $clientquote->truck_required=$request->get('truck_required');
        $clientquote->quote_origin=$request->get('quote_origin');
        $clientquote->quote_destination=$request->get('quote_destination');
        $clientquote->commodity=$request->get('commodity');
        $loading_date=date_create($request->get('loading_date'));
        $format = date_format($loading_date,"Y-m-d H:i:s");
        $clientquote->loading_date = $format;
        $clientquote->save();


        return response()->json([
            'message' => 'Quote Successfully Sent!'
        ], 201);
}

api.php

Route::group([
], function () {
    Route::post('clientquotelanding','ApiController@createClientQuote');
})

Угловой интерфейс показан ниже:

quote.component.ts

import { Component, OnInit, ElementRef, NgZone, ViewChild } from '@angular/core';
import { ApiService } from '../../shared/services/api.service';
import { TokenService } from '../../shared/services/token.service';
import { Router } from '@angular/router';
import { SnotifyService } from 'ng-snotify';


@Component({
  selector: 'app-client-quotes-landing',
  templateUrl: './client-quotes-landing.component.html',
  styleUrls: ['./client-quotes-landing.component.scss']
})
export class ClientQuotesLandingComponent implements OnInit {

  public title = 'Places';
  public addrKeys: string[];
  public addr: object;


  formattedAddress = '';
  truck_types = [];

  public form = {
    first_name : null,
    last_name : null,
    email : null,
    phone : null,
    address : null,
    business_name : null,
    truck_required : null,
    truck_type : null,
    quote_origin : null,
    quote_destination : null,
    commodity : null,
    loading_date : null,
    comment : null,
  };

  public error = {
    'first_name' : null,
    'last_name' : null,
    'email' : null,
    'phone' : null,
    'address' : null,
    'business_name' : null,
    'truck_required' : null,
    'truck_type' : null,
    'quote_origin' : null,
    'quote_destination' : null,
    'commodity' : null,
    'loading_date' : null,
    'comment' : null
  };


  constructor(
    private api: ApiService,
    private token: TokenService,
    private router: Router,
    private notify: SnotifyService,
    private zone: NgZone,
    ) {

     }

  ngOnInit() {
  }

  onSubmit(){
    this.notify.clear();
    var header = {
      'Content-Type': 'application/json'
    }
    return this.api.post('clientquotelanding', this.form, header).subscribe(
      response => {
        this.router.navigateByUrl('/client-quote-landing-success')
        },
      error => this.errorHandle(error),
   );
  }

  tokenHandler(data){
    this.notify.clear();
    console.log(data);
  }

  errorHandle(error){
    this.notify.clear();
    console.log(error);
    this.error = error.error.errors;
  }

}

quote.component.html

  <form class="form-clientquote" #clientquoteForm=ngForm (ngSubmit)="onSubmit()">
    <div class="centered-content">
       <div class="row">
       <div class="col-xs-12">
         <div class="col-xs-6">
         <label for="quote_origin" >Pick-up Location<span style="color:red;"> *</span></label>
         (onSelect)="setAddress($event)" placeholder="Pick-up Location" name="quote_origin" [(ngModel)]="form.quote_origin" #quote_origin="ngModel" [ngClass]="{'is-invalid' : quote_origin.invalid && ((quote_origin.dirty || quote_origin.touched) || clientquoteForm.submitted)}"   required>
                                  <div class="form-feedback" *ngIf="quote_origin.invalid && ((quote_origin.dirty || quote_origin.touched) || clientquoteForm.submitted)" class="invalid-feedback">
         <div style="color:red;" *ngIf="quote_origin.errors?.required"class="alert alert-danger">Pick-up Location is required.</div>
         </div>
        </div>
        <div class="col-xs-6">
        <label for="quote_destination">Destination<span style="color:red;"> *</span></label>
        <input type="text" class="form-control" id="quote_destination" google-place
        (onSelect)="setAddress($event)" placeholder="Destination" name="quote_destination" [(ngModel)]="form.quote_destination" #quote_destination="ngModel" [ngClass]="{'is-invalid' : quote_destination.invalid && ((quote_destination.dirty || quote_destination.touched) || clientquoteForm.submitted)}"   required>
        <div class="form-feedback" *ngIf="quote_destination.invalid && ((quote_destination.dirty || quote_destination.touched) || clientquoteForm.submitted)" class="invalid-feedback">
        <div style="color:red;" *ngIf="quote_destination.errors?.required"class="alert alert-danger">Destination is required.</div>
        </div>
       </div>
     </div>
    </div>
    <br>
    <div class="row">
    <div class="col-xs-12">
     <div class="col-xs-6">
      <label for="truck_type">Truck Type<span style="color:red;"> *</span></label>
      <select class="form-control select2" style="width: 100%;" [(ngModel)]="form.truck_type" #truckType="ngModel" name="truck_type" required>
      <option [ngValue]="null">Choose a Truck Type</option>
      <option [ngValue]="truck_type" *ngFor="let truck_type of truck_types">{{truck_type}}</option>
       </select>
       <div class="form-feedback" *ngIf="truckType.invalid && ((truckType.dirty || truckType.touched) || clientquoteForm.submitted)">
        <div style="color:red;" class="alert alert-danger">Truck Type is required.</div>
        </div>
       </div>
     <div class="col-xs-6">
     <label for="truck_required">Required Truck(s)<span style="color:red;"> *</span></label>
     <input type="number" (keypress)="numberOnly($event)" class="form-control" id="truck_required" placeholder="1,2,3..." min="1" max="20" name="truck_required" [(ngModel)]="form.truck_required" #truck_required="ngModel" [ngClass]="{'is-invalid' : truck_required.invalid && ((truck_required.dirty || truck_required.touched) || clientquoteForm.submitted)}" required>
     <div class="form-feedback" *ngIf="truck_required.invalid && ((truck_required.dirty || truck_required.touched) || clientquoteForm.submitted)" class="invalid-feedback">
       <div style="color:red;" *ngIf="truck_required.errors?.required"class="alert alert-danger">Required Truck(s) is required.</div>
        </div>
     </div>
    </div>
  </div>

  <div class="row">
   <div class="col-xs-12">
     <div class="col-xs-12">
      <div class="btn-group" style="text-align: center;">
         <button style="margin:5px" (keyup.enter)="onSubmit()" type="submit" class="btn btn-success"> Save</button>
      </div>
      </div>
     </div>
    </div>
 </form>

В настоящее время, когда я нажимаю кнопку «Отправить», она сохраняется в базе данных. Однако я хочу немедленно отобразить данные, которые сохраняются в базе данных. Как мне этого добиться?

1 Ответ

0 голосов
/ 14 октября 2019

изменить возврат функции createClientQuote на следующий

        return response()->json([
            'message' => 'Quote Successfully Sent!','data' =>  $clientquote
        ], 201);

этот ответ вернет объект clientquote и обработает ответ объекта clientquote в Angular.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...