比方說,我建有Laravel的API,允許索引和存儲英雄在我的數據庫。AngularJS 2.0 - 數據發佈到Laravel方法
這是我的存儲方法看起來像在我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獲取返回的結果?
換句話說:我該如何使用角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>
AngularJS得到'500(內部服務器錯誤)',我覺得沒有監守數據發送到我的laravel API。我可以如何將我的表單數據發送到api?您的答案中沒有提及任何表單輸入數據。這是我的形式:'
'。 AddHero()方法與您評論的代碼非常相似。 – TheUnreal檢查您的路線路徑是否正確。你在路由文件「**/heroWorld/public/api/v1/heroes **」中有這個嗎? – oseintow
我將其更改爲正確的URL,是的,我的路由文件中包含它。如果我沒有,我想它會返回404. – TheUnreal