Do I have to create all the classes returned when consuming a JSON web service in Angular/Typescript?

I would like to access this service:

https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY

I am interested in extracting only two pieces of data:

        "location" : {
           "lat" : -10.6872332,
           "lng" : -37.4329352

However, this service returns data in 11 different classes. My question is: Is it necessary to navigate through all these classes just to access 2 fields?

Currently, my method is stuck at this point.

getCoord(city:string): Observable<any>
{
    return this._http.get(this.urlBase+cidade+this.key)
        //.map((response: Response) => <any>response.json())
        .do(data => console.log('All: ' + JSON.stringify(data)));
}

Answer №1

No, I do not. In order to utilize specific properties of JSON, all that is needed is to create a class or path to access the data. In my scenario, to retrieve the location data {lat: number; lng: number;}, I created an object/class along with a few interfaces:

interface Location{lat: number; lng: number;}
interface Geometry{location: Location;}
interface Result{geometry: Geometry;}

export class GeocoderResult {
    results: Array<Result>;
    status: string;

    constructor() {
        this.results = new Array<Result>();
    }
}

In my .TS file, the method works perfectly:

key: string = '&key=XXX';
urlBase: string = 'https://maps.googleapis.com/maps/api/geocode/json?address=';
city: string = 'yourCityName';

getCoord(city: string): any
{
    return this._http.get<GeocoderResult>(this.urlBase+city+this.key)
    .subscribe(data => {    
        return data.results[0].geometry.location;
        //console.log('geo = ', data.results[0].geometry.location);
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to vertically aligning text in an overlay using CSS within Angular 2

I currently have an overlay on my page that displays a spinner (an Angular material component) and accompanying text. This overlay covers the entire page and prevents clicking on elements below it. The spinner is positioned in the center of the page, and ...

Encountering an issue in Angular 8 flex-layout 8: Unable to export member ɵNgClassImpl

I encountered an issue while trying to install flex-layout 8.0.0-beta.26 in my Angular 8 project. The error I received during the build process is as follows: ERROR in node_modules/@angular/flex-layout/extended/typings/class/class.d.ts(9,19): error TS2305 ...

Creating an interactive checkbox input field utilizing a JSON-driven database

Can someone assist me with creating dynamic checkboxes? I have JSON data structured as follows: [ { "categoryName": "Category 1", "items": [ { "value": "value1", "label": "label1" }, { "value": "value2" ...

Assign a class to an Angular component's host element without any conditions

In my Angular project, I have a component where I need to apply a class unconditionally. To achieve this, the host property within the @Component decorator can be used: import { Component } from '@angular/core'; @Component({ selector: 'ap ...

The error message, "Property 'message' is not found on type 'ErrorRequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>.ts(2339)", indicates that the requested property is not present in the specified type

Hello there! Recently, I implemented a custom error handling middleware in my Node.js TypeScript application. However, I encountered an issue where it is showing an error stating that 'message' does not exist on type 'ErrorRequestHandler&apo ...

Angular is a powerful framework that enables the creation of dynamic user interfaces. One of its many

Looking to implement a Material table with expandable rows in Angular. table-tree.html <table mat-table [dataSource]="dataSource" multiTemplateDataRows class="mat-elevation-z8" > <ng-container matColumnDef="{{co ...

Rule in Eslint for Typescript that enforces explicit typing and prohibits the use of implicit "any

Starting a fresh typescript project with eslint, I'm facing an issue in setting up eslint rules for the tsc command to run smoothly without errors. Specifically, I'm encountering difficulty with the "noImplicitAny" rule defined in tsconfig.json, ...

Exploring the various form types supported by 'react-hook-form'

I utilized react hooks form to create this form: import React from "react"; import ReactDOM from "react-dom"; import { useForm, SubmitHandler } from "react-hook-form"; import "./styles.css"; function App() { type ...

How do React Native proxies differ from vanilla React proxies in their functionality?

Trying to retrieve data from an API running locally on port 5000 of my device, I recalled setting the proxy in package.json when working on React web applications: "proxy": "https://localhost:5000" Attempting to fetch information f ...

Python: convert a list generator to be serializable in JSON format

Is there a way to concatenate a large list of JSON files into a single huge JSON array? I have 5000 files and 550,000 list items in total. Initially, I attempted using jq, but it seems that jq -s is not suitable for handling such a large input size. jq - ...

Running 'npm start' results in an error linked to package.json

Upon attempting to launch my React application with 'npm start', an error message appeared in the terminal: npm ERR! code ENOENT npm ERR! syscall open npm ERR! path /Users/louis/afrikalink/package.json npm ERR! errno -2 npm ERR! enoent ENOENT: no ...

Trouble with AJAX not properly fetching PHP JSON response

I recently encountered an issue with my jQuery AJAX request that sends user input to a PHP file. Initially, the code worked perfectly fine but adding "dataType: 'json'" caused it to malfunction. Here's how I set it up: $.ajax({ url: url ...

Clear the input field once an item has been successfully added to the array

I'm working on a CRUD application using an array. Once I add an item to the array, the HTML input field doesn't clear or reset. I've searched online but couldn't find a reset method in Angular. How can I clear the input field after addi ...

What steps should I follow to have my edit form component extract values from HTML in Angular?

I created a detailed listing page that includes a picture URL, title, phone number, description, and price. When the user clicks on the Edit button, it redirects them to a page with input forms for each of these fields. The form automatically populates the ...

Having difficulty interpreting the JSON response sent by Google

I've been having trouble parsing a Json response from this specific URL. I've tried using SBJsonParser, MTJSON, and another parser, but unfortunately, all three have returned NULL in my case. apiUrlStr = @"http://maps.google.com/maps?output=drag ...

Issue encountered in Vite Preview: Uncaught (in promise) SyntaxError: JSON.parse found an unexpected character at the beginning of the JSON data, line 1 column 1

Encountering the error message Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data when running vite preview after running vite build. https://i.sstatic.net/61Y9t.png Here is my vite.config.js: import { ...

Getting the initial value of a node from a JSON response by utilizing Groovy

I am attempting to extract the first node value (ResourceItemID which is 2290) from my JSON response. Here is how my Response looks: { "Success": true, "TotalRecords": 41, "RoomSearchResult": [ { "ResourceItemID": 2290 ...

Checking radios or checkboxes will always result in a null value when retrieving their form values

After following the instructions in the Angular 2 cookbook for dynamic forms, I encountered an issue with the radios and checkboxes. Despite checking them, they always return a null value. Interestingly, the touched properties of the radios and checkboxes ...

What is the best way to transfer an array of intricate objects to a different page in PHP?

In my code, I am working with an array called $batchRequest which has a structure like this: array(5) { [0]=> array(0) { } [1]=> object(Facebook\FacebookRequest)#18 (9) { ["app":protected]=> object(Facebook\FacebookApp ...

Incorporating a new parameter into the JSON response from SoundCloud

Currently, I am in the process of developing an app utilizing the SoundCloud JavaScript API. My approach involves fetching the JSON data from: http://api.soundcloud.com/resolve.json?url=http://soundcloud.com/matas/hobnotropic&client_id=YOUR_CLIENT_ID ...