Transferring data to a different module

I'm currently working on an Angular program where I am taking a user's input of a zip code and sending it to a function that then calls an API to convert it into latitude and longitude coordinates. Here is a snippet of the code:

home.component.html

<div class="center" style="margin-top:50px;">
        <label for="ZipCode"><b>Zip Code</b></label>        
    </div>

    <div class="center">
        <input name="zipcode" #zipcode id="zipcode" type="text" placeholder="Enter Zip Code" maxlength="5">
    </div>
<div class="center" style="margin-top:100px;">
        <button class="button button1" (click)="getCoords(zipcode.value)" ><b>Retrieve Data</b></button>
    </div>

The next step involves calling the function with the API and navigating to the stations component/page:

home.component.ts

export class HomeComponent implements OnInit {
    
    constructor(
        private router: Router
    ){}

    ngOnInit(): void {
    }

    getCoords(val: any){
        var url = "http://www.mapquestapi.com/geocoding/v1/address?key=MYKEY&location=" + val;

        fetch(url)
        .then((res) => res.json())
        .then((data) => {
            var lat = data.results[0].locations[0].displayLatLng.lat;
            var long = data.results[0].locations[0].displayLatLng.lng;

            this.router.navigate(["/stations"])
        })        
    }
}

stations.component.ts - Work in progress, unsure how to proceed at the moment.

import { Component, Input, OnInit } from '@angular/core';


@Component({
  selector: 'app-stations',
  templateUrl: './stations.component.html'
})

export class StationsComponent implements OnInit {
  

  ngOnInit(): void {
  }

}

Everything functions correctly as intended. My challenge now lies in passing the latitude and longitude values to another component/page for further calculations. I have researched extensively but haven't found a simple solution in Angular. Any suggestions on how to accomplish this task?

Answer №1

If you want to handle query parameters, you can utilize the following code snippet:

   getCoords(val: any){
        var url = "http://www.mapquestapi.com/geocoding/v1/address?key=MYKEY&location=" + val;

        fetch(url)
        .then((res) => res.json())
        .then((data) => {
            var lat = data.results[0].locations[0].displayLatLng.lat;
            var long = data.results[0].locations[0].displayLatLng.lng;

            this.router.navigate(["/stations"], {queryParams :{ dataLat : lat, dataLong : long}} )
        })        
    }

In your stations.component.ts, you can use ActivatedRoute like so:

import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';


@Component({
  selector: 'app-stations',
  templateUrl: './stations.component.html'
})

export class StationsComponent implements OnInit {
  
  getLat:any;
  getLong:any;

  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {
    this.route.queryParams.subscribe(params => {
      this.getLat = params.dataLat;
      this.getLong = params.dataLong;
      console.log(params); 
    });
  }
}

For more information on this topic, check out the Angular Router Guide and this resource.

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

Enhance your drag and drop experience with Angular CDK by customizing placeholder height dynamically

I am looking to dynamically set the placeholder height based on the height of the dragging element. Currently, I have a static placeholder height set to the smallest possible element height. I have searched for information on how to achieve this dynamic h ...

Using Angular to store checkbox values in an array

I'm currently developing a feature that involves generating checkboxes for each input based on the number of passengers. My goal is to capture and associate the value of each checkbox with the corresponding input. Ultimately, I aim to store these valu ...

Azure Function (.NET 7, v4) encountering Cross-Origin Resource Sharing problem

I am experiencing a CORS problem with my Azure function written in C# using .NET 7. It is being called from my Angular application. Interestingly, the same function works fine when called from Postman with the same request body as the Angular application. ...

Tips for parsing through extensive JSON documents containing diverse data types

In the process of developing an npm package that reads json files and validates their content against predefined json-schemas, I encountered issues when handling larger file sizes (50MB+). When attempting to parse these large files, I faced memory allocati ...

What is the best way to set the generics attribute of an object during initialization?

Below is the code that I have: class Eventful<T extends string> { // ↓ How can I initialize this attribute without TypeScript error? private eventMap: Record<T, (args?: any) => void> = ? } Alternatively, class Eventful<T extends st ...

When using this.$refs in Vue, be mindful that the object may be undefined

After switching to TypeScript, I encountered errors in some of my code related to: Object is possibly 'undefined' The version of TypeScript being used is 3.2.1 Below is the problematic code snippet: this.$refs[`stud-copy-${index}`][0].innerHTM ...

Tips for utilizing regex to locate words and spaces within a text?

I'm feeling so frustrated and lost right now. Any help you can offer would be greatly appreciated. I am currently dealing with an issue in Katex and Guppy keyboard. My goal is to create a regex that will identify the word matrix, locate the slash that ...

Error: Unable to locate specified column in Angular Material table

I don't understand why I am encountering this error in my code: ERROR Error: Could not find column with id "continent". I thought I had added the display column part correctly, so I'm unsure why this error is happening. <div class="exa ...

Modifying a Component's Value in its Template Based on an IF Condition in Angular 6

How can I display or hide the 'separator-container' based on a specific condition in the row data? The condition to satisfy is mentioned as "myConditionCheck" in the 5th line of code. I attempted to achieve this by using "isWarningSeperatorVisib ...

Conditional types can be used as type guards

I have this simplified code snippet: export type CustomType<T> = T extends Array<unknown> ? {data: T} : T; function checkAndCast<T extends Array<unknown>>(value: CustomType<T>): value is {data: T} { return "data" ...

One way to incorporate type annotations into your onChange and onClick functions in TypeScript when working with React is by specifying the expected

Recently, I created a component type Properties = { label: string, autoFocus: boolean, onClick: (e: React.ClickEvent<HTMLInputElement>) => void, onChange: (e: React.ChangeEvent<HTMLInputElement>) => void } const InputField = ({ h ...

"Exploring the depths of Webpack's module

This is my first venture into creating an Angular 2 application within MVC Core, utilizing TypeScript 2.2, Angular2, and Webpack. I have been closely following the Angular Documentation, but despite referencing the latest NPM Modules, I encounter errors w ...

Unable to locate the JSON file in the req.body after sending it through an HTTP post request

I have been working on implementing a new feature in my application that involves passing a JSON file from an Angular frontend to a Node backend using Express. The initial code reference can be found at How do I write a JSON object to file via Node server? ...

Issue C2039: 'IsNearDeath' cannot be found within 'Nan::Persistent<v8::Object,v8 ::NonCopyablePersistentTraits<T>>'

After updating my nodejs to v12.3.1, I encountered errors when attempting to execute npm install in my project directory. error C2059: syntax error: ')' (compiling source file ..\src\custo m_importer_bridge.cpp) error C2660: 'v8 ...

The type 'Requireable<string>' cannot be matched with the type 'Validator<"horizontal" | "vertical" | undefined>'

code import * as React from 'react'; import * as PropTypes from 'prop-types'; interface ILayoutProps { dir?: 'horizontal' | 'vertical' }; const Layout: React.FunctionComponent<ILayoutProps> = (props) => ...

Traverse through an array of objects with unspecified length and undefined key names

Consider the following object arrays: 1. [{id:'1', code:'somecode', desc:'this is the description'}, {...}, {...}] 2. [{fname:'name', lname:'last name', address:'my address', email:'<a h ...

The request to DELETE the employee on the server at http://localhost:3000/employees/$%7Bid%7D could not be processed because it was not found

removeEmployee(id: number): Observable<any> { return this._http.delete('http://localhost:3000/staff/${id}'); } } error:HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: 'Not Found', url: 'http://localhost:30 ...

I'm curious about the correct method for updating a parent component using a shared service within the ngOnInit function in Angular version 13

There have been instances where I encountered a scenario multiple times, where I utilize a shared service within the ngOnInit of a component to update a value in another component, specifically its parent. This often leads to the well-known Error: NG0100: ...

Displaying a dynamic flag icon in a span element based on the selection from a mat-select

I am working on a mat-select component and I want to dynamically change a flag icon inside a span element in the mat-label based on the selected option. Currently, the initial flag is displayed correctly, but when I click on a different option, the flag d ...

"When attempting to render a Node inside the render() method in React, the error message 'Objects are not valid as a React child' is

On my webpage, I have managed to display the following: export class OverworldComponent extends React.Component<OverworldComponentProps, {}> { render() { return <b>Hello, world!</b> } } However, instead of showing Hello, ...