I'm trying to set up an Angular application that is going to pull restaurants based on a search query and list out their names but I can't get the Google Places API to work in my Angular component/service.
Here's my service code:
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class RestaurantsApiService {
API_KEY:string ="MYKEY";
constructor(private httpClient: HttpClient) { }
public getRestaurants(){
return this.httpClient.get(`https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurants+in+Sydney&key=${this.API_KEY}`);
}
}
And here's the code from my component:
import { Component, OnInit } from '@angular/core';
import { RestaurantsApiService } from '../restaurants-api.service';
@Component({
selector: 'app-restaurants',
templateUrl: './restaurants.component.html',
styleUrls: ['./restaurants.component.css']
})
export class RestaurantsComponent implements OnInit {
restaurantsResults;
constructor(private restaurantsAPI: RestaurantsApiService) { }
ngOnInit() {
this.restaurantsAPI.getRestaurants().subscribe((data) => {
console.log(data);
this.restaurantsResults = data['results'];
})
}
}
And my component's html:
<p>Restaurants:</p>
<div *ngFor="let restaurant of restaurantsResults">
<h2>{{restaurant.name}}</h2>
</div>
It's all very simple and when I load that API link into my browser I get the JSON results back. But for some reason when pulling from my angular application I'm just getting this error in the console:
"Access to XMLHttpRequest at 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurants+in+Sydney&key=MYKEY' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
Why is this happening? To be honest I'm doing this for a class where we we're given an example with a different API and that one worked perfectly (got the JSON from the API and displayed the information I needed) so I can't understand why this one isn't working.
I have been searching for an answer but most of the answers don't relate to angular and mention using the client api but I don't understand how to do that for my purposes since that api is scripts when for this I need to gather data from the json file which is loading in my browser without the angular.