Bonjour à tous,
Je fais un api symfony/angular sans authentification.
Le problème c'est que ma requête http échoue avec angular mais fonctionne avec un navigateur ou postman.
Service angular:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import { Injectable } from '@angular/core';
import { Product } from '../Models/product'
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ProductService {
httpOptions = {
'Content-type': 'application/json'
}
products: Product[] = []
constructor(private http: HttpClient) { }
getProducts(){
return this.http.get<[Product]>('localhost:8000/products');
}
} |
Le component ou j'appelle le service
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import { Component, OnInit } from '@angular/core';
import { Product } from '../Models/product'
import { ProductService } from '../Service/product.service'
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
constructor(private productService: ProductService,
private http: HttpClient
) { }
ngOnInit() {
this.productService.getProducts().subscribe(
data => {console.log(data);}
);
}
} |
Ma fonction symfony qui est correct puisque je récupère bien du json dans le navigateur et postman (toJson contient le serializer symfony)
1 2 3 4 5 6 7 8 9 10 11 12
|
/**
* @Route("/", name="product_getAll", methods={"GET"})
*/
public function getProducts(ProductRepository $productRepository)
{
return new JsonResponse(
$this->toJson($productRepository->findAll()),
JsonResponse::HTTP_OK,
['Content-type' => 'application/json', 'Access-Control-Allow-Origin' => '*']
);
} |
Et l'erreur
ERROR {
}error: error { target: XMLHttpRequest, isTrusted: true, lengthComputable: false,
}headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) }message: "Http failure response for localhost:8000/products: 0 Unknown Error"name: "HttpErrorResponse"ok: falsestatus: 0statusText: "Unknown Error"url: "localhost:8000/products"__proto__: Object {
} core.js:6014:19
Merci de votre aide
Partager