AngularJS 2.0 - 将数据发布到Laravel方法

时间:2016-03-28 12:17:04

标签: laravel angular

假设我使用Laravel构建了一个API,允许在我的数据库中索引和存储英雄

这就是我的laravel英雄控制器中我的商店方法的样子:

public function store(Request $request)
    {

        $hero = new Hero;
        $hero->name = $request->name;
        $hero->description = $request->description;
        $hero->avatar = "None";
        $hero->save();

        $heroes = Hero::paginate(5);
        return view('/heroes/index', [
        'heroes' => $heroes
    ]);
    }

上述方法将请求数据发送到我的数据库中的右侧字段。

我的问题是:我如何操作表单数据并将表单数据发送到此方法并使用Angular 2.0获取返回的结果?

换句话说:我如何使用Angular 2.0来处理我的laravel API?

这是我用于显示英雄列表的angular2.0方法:

getHeroes() {
      this.http.get('http://127.0.0.1/heroWorld/public/api/v1/heroes')
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.heroes = data;
        },
        err => console.error(err),
        () => console.log('done');
      );
  }

所以..如何从我的角度创建一个?

    addHero() {

      let headers = new Headers();
    headers.append('Content-type', 'application/x-www-form-urlencoded');

    let formPayload = new URLSearchParams();
    formPayload.set('name', name);
    formPayload.set('description', description);

       this.http.post('http://127.0.0.1/heroWorld/public/heroes', formPayload.toString(), { headers: headers })
  .map((res:Response) => res.json())
  .subscribe(
        data => { this.heroes = data;
        },
        err => console.error(err),
        () => console.log('done');
      );
  }

错误:failed to load resource: the server responded with a status of 500 (Internal Server Error)

我的角色形式:

<form method="post">
    Hero name: <input type="text" name="name" [ngModel]="name"><br/>
    Hero description: <input type="text" name="description" [ngModel]="description">
    <button (click)="addHero()" class="btn btn-primary">Add this hero!</button>
    </form>

我的laravel工作形式:

<!-- New Hero Form -->
        <form action="http://127.0.0.1/heroWorld/public/heroes" method="POST" class="form-horizontal">
            <input type="hidden" name="_token" value="knUS8vUxihTj4YJhjVkqmRBJJkVDDCABIZaRwXhN">

            <!-- Hero Name -->
            <div class="form-group">
                <label for="hero-name" class="col-sm-4 control-label">Hero Name</label>

                <div class="col-sm-6">
                    <input type="text" name="name" id="hero-name" class="form-control">
                </div>
            </div>

            <!-- Hero Description -->
            <div class="form-group">
                <label for="hero-description" class="col-sm-4 control-label">Hero Description</label>

                <div class="col-sm-6">
                    <input type="text" name="description" id="hero-description" class="form-control">
                </div>
            </div>

            <!-- Add Hero Button -->
            <div class="form-group">
                <div class="col-sm-offset-3 col-sm-6">
                    <button type="submit" class="btn btn-default">
                        <i class="fa fa-plus"></i> Add Hero
                    </button>
                </div>
            </div>
        </form>

2 个答案:

答案 0 :(得分:0)

首先以角度向laravel发送数据,您需要将请求从“发布”更改为“发布”。

getHeroes() {
  this.http.post('http://127.0.0.1/heroWorld/public/api/v1/heroes')
  .map((res:Response) => res.json())
  .subscribe(
    data => { this.heroes = data;
    },
    err => console.error(err),
    () => console.log('done');
  );

}

在laravel store函数中,您需要发送一个json响应,因为您正在以json格式使用api。

public function store(Request $request)
{

    $hero = new Hero;
    $hero->name = $request->name;
    $hero->description = $request->description;
    $hero->avatar = "None";
    $hero->save();

    $heroes = Hero::paginate(5)->toArray();
    return response()->json($heroes);
]);
}

答案 1 :(得分:0)

发送带有JSON有效负载的请求:

var headers = new Headers();
headers.append('Content-Type', 'application/json');

var obj = {
  name: this.name,
  description: this.description,
  '_token': this.token
};

 this.http.post('http://127.0.0.1/heroWorld/public/api/v1/heroes', JSON.stringify(obj), { headers: headers })
  .map((res:Response) => res.json())
  .subscribe(
    data => {
      this.heroes = data;
    },
    err => console.error(err),
    () => console.log('done');
  );

不要忘记导入Headers类和Http one:

import { Http, Headers } from 'angular2/http';

修改

如果要发送表单,请使用以下命令:

let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');

let formPayload = new URLSearchParams();
formPayload.set('name', this.name);
formPayload.set('description', this.description);
formPayload.set('_token', this.token);
 this.http.post('http://127.0.0.1/heroWorld/public/api/v1/heroes', formPayload.toString(), { headers: headers })
  .map((res:Response) => res.json())
  .subscribe( ... );

和相应的表格:

<form>
  <input type="hidden" name="_token" [ngModel]="token"
         value="knUS8vUxihTj4YJhjVkqmRBJJkVDDCABIZaRwXhN">
  Hero name: <input type="text" name="name" [ngModel]="name"><br/>
  Hero description: <input type="text" name="description" [ngModel]="description">
  <button (click)="addHero()" class="btn btn-primary">Add this hero!</button>
</form>