我正在尝试从Angular前端的Laravel API访问数据。 要接收所需的数据,我必须将“ id”作为POST发送到URL,URL进而查询数据库并将结果作为JSON返回。 使用POSTMAN和其他API测试器工具,我已验证端点正常运行。 当我尝试从Angular发送POST请求时,我没有在Laravel API上收到POST数据,并且出现以下错误。
请注意,我已从代码中删除了实际的网址
(1/1) ErrorException
Trying to get property of non-object
in ServiceRequestController.php line 209
at HandleExceptions->handleError(8, 'Trying to get property of non-object', '/home/removed_name/public_html/KoiKaam/app/Http/Controllers/ServiceRequestController.php', 209, array('request' => object(Request), 'serviceRequests' => object(Collection), 'id' => null, 'category' => null, 'cats' => object(Collection), 'cat' => null))
in ServiceRequestController.php line 209
在POSTMAN和Android应用程序上测试的实际结果应为this (a screenshot of the result)
这是我用来获取结果的角度服务的代码
import { Http, Headers, RequestOptions } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { BuyDeliverRequests } from '../classes/buy-deliver-requests';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
const httpPostOptions = {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
};
@Injectable()
export class BuyDeliverRequestsService {
private url = 'http://removed_name/KoiKaam/public/api/serviceRequestByCategory'
constructor(private http: HttpClient) { }
getBuyDeliverServices(serverResponse: BuyDeliverRequests) {
return this.http.post(this.url, {id: 1}, httpPostOptions).subscribe(
data => { serverResponse = data.data; console.log(data); },
err => console.log(err),
() => console.log('Successful')
);
}
}
这是URL /端点转到的功能,用于获取结果:
/*this function returns all rows of service request wrt category with their picture paths from service request pictures table
and bids on that request request*/
public function showServiceRequestbyCategory(Request $request)
{
$serviceRequests = new Collection();
$id = $request->id;
$category = Category::find($id);
$this->categories->push($category);
$cats = $this->getChilds($id);
try{
foreach ($cats as $cat){
$srv = $this->getServiceRequest($cat->id); //This is line 209 from the error
foreach ($srv as $service){
$serviceRequests->push($service);
}
}
$response["message"] = "Post Created Successfully";
$response["error"] = false;
$response["data"] = $serviceRequests;
return json_encode($response);
}
catch (QueryException $e){
$response["message"] = $e->errorInfo[2];
$response["error"] = true;
$response["sja"] = "2nd";
return json_encode($response);
}
}
以下是Laravel识别错误的行上正在调用的函数
private function getServiceRequest($category_id){
try{
$serviceRequest = ServiceRequest::where([['category_id','=', $category_id],
['in_process_flag', '=', false]])->paginate(5);
if($serviceRequest){
return $serviceRequest;
}
}
catch(QueryException $e){
}
}
答案 0 :(得分:0)
经过大量的搜索,终于指出了问题并找到了解决方法
当Angular 5通过POST发送数据时,它以JSON形式发送。我在Laravel End上的控制器期望使用FORM数据,可以通过$request->id
有两种解决方法。在Angular一侧或Laravel一侧。
Laravel
这真的很简单,我们首先需要将其存储在数组中,而不是直接访问$request
$data= $request->json()->all();
然后我们可以使用$data
作为关联数组来获取所需的数据,例如如果我想使用 id ,我会
$id= $data['id'];
,然后根据需要使用$ id
角度
我们首先需要序列化存储数据的对象,然后再将其发布到Laravel后端。 jQuery为此具有自己的功能$.param()
,但是由于我们使用的是angular,因此我发现了一个自定义函数,其功能相同。
formatData(data) {
let returnData = '';
let count = 0;
for (let i in data) {
if (count == 0) {
returnData += i + '=' + data[i];
} else {
returnData += '&' + i + '=' + data[i];
}
count = count + 1;
}
return returnData;
}
因此,要发送数据,我必须如下编辑Service类功能
getServicesByCategory(category_id: number) {
let data = {id: category_id};
let body = this.formatData(data);
return this.http.post(this.url, body, httpPostOptions);
}
在另一个问题here
上找到了此功能