如何解析后端的数据

时间:2017-06-22 14:49:45

标签: laravel

我使用Angular2作为我的前端和laravel用于我的后端,我在将数据保存到数据库时遇到了问题

Order[](ex prodNameprodDesc)中的每个键都与数据库中的列名相同,因此我尝试循环请求并保存数据但它不起作用

public function Order(Request $request) {
    $input = $request->all();
    $order = new Order;

    foreach ($input as $key => $value) {
        if (array_key_exists($key, $input) && !empty($value)) {
         $order->$key = $value;
     }
   }
}
if($order->save()) {
    return response()->json(['order' => $order], 201);
}

order.interface.ts

export interface Order {
  prodName: string;
  prodDesc: string;
}

将项目添加到订单

addToOrder.component.ts

orders = [] as Order[];

saveItem(): void {
  this.orders.push({prodName: this.prodName, prodDesc: this.prodDesc});
  this.dataService.save(this.orders).then(() => {
    this.navCtrl.pop(Search);
  });
}

每个项目如何存储在存储

order.storage.ts

save(data : Order[]): Promise<any> {
  return this.getData().then((products: any[]) => {
  if (products) {
   products = products.concat(data);
   return this.storage.set('products', products);
  }
  return this.storage.set('products', data);
  });
}

我如何从存储中检索订单

order.component.ts

private order = [] as Order[];

constructor(public dataService: OrderStorage, public OrderService: OrderService) {

  this.dataService.getData().then((products) => {
    if (products) { 
    this.order = products;
    }
  });
}

onSubmit() {
  this.OrderService.submit(this.order)
    .subscribe();
}

将数据发布到后端

order.service.ts

submit(order: Order[]): Observable<any> {
  return this.http.post(localapi.app, order)
    .map(
      (response: Response) => {});
}

正在发送的order数据的结构

enter image description here

检索后端的数据

public function Order(Request $request) {
    $input = $request->all();
    var_dump($input);
}

var_dump输出

enter image description here

1 个答案:

答案 0 :(得分:1)

实际上是foreach ($input as $key => $arr),那么你可以使用你的循环:

foreach ($input as $arr) {
    foreach ($arr as $key => $value) {
       if (array_key_exists($key, $arr) && !empty($value)) {
            $order->$key = $value;
       }
    }
}

您在循环中遇到的第一组元素是数组,然后您可以将属性从数组中循环。