Я пытаюсь получить доступ к данным из Laravel API для моего внешнего интерфейса Angular.Чтобы получить необходимые данные, я должен отправить «id» в виде POST на URL, который, в свою очередь, запрашивает базу данных и возвращает результат в виде JSON.ИСПОЛЬЗУЯ POSTMAN и другие инструменты тестирования API, я убедился, что конечная точка работает правильно.Когда я пытаюсь отправить POST-запрос от Angular, я не получаю POST-данные от моего Laravel API, и выдается следующая ошибка:
Обратите внимание, что я удалил фактические URL-адреса из кода
(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 (снимок экрана с результатом)
Это код угловой службы IЯ использую для получения результатов
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){
}
}