Unable to transfer the form value to the service and City value cannot be updated

I am new to the world of Angular and I am attempting to create a basic weather application. However, I am encountering issues when trying to pass the city value from the form on ngSubmit to the API service. I have attempted to use an Emitter Event to transmit the value, but it appears that the city value is not being updated in the service. Is there a method for sending this value to the API service and updating the city name?

weather-card.component.html

<div class="input-container">
  <app-weather-form></app-weather-form>
</div>
<div *ngFor="let item of weathers[0]; first as isFirst">
  <div *ngIf="!isFirst">
    <mat-card class="mat-card">
      <p><strong>Name :</strong>{{ item.name }}</p>
      <p><strong>State :</strong> {{ item.region }}</p>
      <p><strong>Country :</strong>{{ item.country }}</p>
      <p><strong>Latitude:</strong> {{ item.lat }}</p>
      <p><strong>Longitude:</strong> {{ item.lon }}</p>
    </mat-card>
  </div>
</div>

weather-card.component.ts

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { WeatherService } from '../../services/weather.service';
import { WeatherData } from '../../models/weather';
import { WeatherFormComponent } from '../weather-form/weather-form.component';

@Component({
  selector: 'app-weather-card',
  templateUrl: './weather-card.component.html',
  styleUrls: ['./weather-card.component.scss'],
})
export class WeatherCardComponent implements OnInit {
  weathers: any = [];

  constructor(public weatherService: WeatherService) {}

  ngOnInit() {
    this.getUsers();
  }

  getUsers() {
    this.weatherService.getWeatherData().subscribe((data) => {
      this.weathers = Object.entries(data);
      console.log(this.weathers);
    });
  }
}

weather-form.component.html

<form (ngSubmit)="submit()">
  City:<br />
  <input type="text" name="city" [(ngModel)]="name" /><br />
  <input type="submit" value="Submit" />
</form>

weather-form.component.ts

import { WeatherService } from 'src/app/services/weather.service';
import { WeatherData } from 'src/app/models/weather';

@Component({
  selector: 'app-weather-form',
  templateUrl: './weather-form.component.html',
  styleUrls: ['./weather-form.component.scss'],
})
export class WeatherFormComponent implements OnInit {
  @Output() onSelection: EventEmitter<any> = new EventEmitter();
  weather!: WeatherData;
  name!: '';
  constructor(private weatherService: WeatherService) {}

  ngOnInit(): void {}

  submit() {
    this.weatherService.getWeatherData().subscribe((data: any) => {
      this.onSelection.emit(this.weather);
    });
  }
}

weather.ts

export interface WeatherData {
  name: string;
  region: string;
  country: string;
  humidity: string;
  localtime: string;
  lat: string;
  lon: string;
}

weather.service.ts

import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import {
  HttpClient,
  HttpHeaders,
  HttpErrorResponse,
} from '@angular/common/http';

let serviceUrl: String = 'http://api.weatherapi.com/v1/current.json';
let apiKey: String = 'someAPIKey'; // insert your API key here
let name: String = 'mumbai';
@Injectable({
  providedIn: 'root',
})
export class WeatherService {
  constructor(private http: HttpClient) {}

  getWeatherData() {
    return this.http.get(
      serviceUrl + '?key=' + apiKey + '&q=' + name + '&aqi=no'
    );
  }
}

In the weather.service.ts file, I wanted to change the value of name by passing the value from form and pass it to the URL. Currently, I have hard coded the value.

Answer №1

By implementing strong typing on the form interface, you have omitted the city value in your interface definition.

export interface WeatherData {
      name?: string;
      region?: string;
      country?: string;
      humidity?: string;
      localtime?: string;
      lat?: string;
      lon?: string;

      /// add
      city?: string;
}

When utilizing strong typing, any unknown data is disregarded.

Answer №2

Your city input is linked to the name property in the WeatherFormComponent, however, this property is not being utilized. To utilize this value in a function of the WeatherService, simply pass it as a parameter:

WeatherFormComponent:

submit() {
    this.weatherService.getWeatherData(this.name).subscribe((data: any) => {
      this.onSelection.emit(this.weather); // The purpose of this event is unclear
    });
  }

WeatherService:

getWeatherData(name?: string) {
   // Handle the case where 'name' is undefined
    return this.http.get(
      serviceUrl + '?key=' + apiKey + '&q=' + name + '&aqi=no'
    );
  }

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

In Next.js, a peculiar issue arises when getServerSideProps receives a query stringified object that appears as "[Object object]"

Summary: query: { token: '[object Object]' }, params: { token: '[object Object]' } The folder structure of my pages is as follows: +---catalog | | index.tsx | | products.tsx | | | \---[slug] | index.tsx | ...

An unusual occurrence of events may occur when serverTimestamp fields are added to a Firestore collection alongside new elements

I've developed a web application where users can share messages on a specific topic. I'm utilizing Firebase as the backend with data stored in Firestore. Each message object contains an ID, content, creation timestamp, and last updated timestamp. ...

Ways to assign a boolean value to HTML using Angular?

Can someone help me set the initial value of showProduct to false for the app-product HTML selector? showProduct:boolean = false; <button (click)="showProduct=!showProduct">Show Product</button> <div *ngIf="!showProduct"> <app-p ...

Typescript Error:TS2345: The argument '{ theme: string; jsonFile: string; output: string; }; }' is not compatible with the parameter type 'Options'

Encountering an error mentioned in the title while using the code snippet below: import * as fs from 'fs' import { mkdirp } from 'mkdirp' import * as report from 'cucumber-html-reporter' const Cucumber = require('cucumber ...

Verify if all the words commence with a certain character using regular expressions

I am working on form validation using Angular, and I am trying to verify if all words in a string start with the letter 'Z'. I am implementing this using a pattern so that I can dynamically change the input's class. So far, this is what I h ...

Troubleshooting: Why is my ng serve command in Angular 5 not

Whenever I try to run ng serve, an error pops up ng : The term 'ng' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is ...

Could you specify the type of useFormik used in formik forms?

For my react formik form, I have created multiple components and now I am looking for the right way to pass down the useFormik object to these components. What should be the correct type for formik? Main Form const formik = useFormik({ ... Subcomponent ...

Insert a blank row at the top of the grid in Wijmo for Angular 2

I am attempting to insert a new empty row at the start of the grid when an external button is clicked. The grid is displaying correctly. <wj-flex-grid #flex [itemsSource]="data" [isReadOnly]="true" [headersVisibility]="'Column' ...

Is it possible to add new values to a GraphQL query?

I am currently utilizing GraphQL and Typeorm in conjunction with an Oracle Database, specifically focusing on retrieving all data from a specific table. The query that is being executed is: SELECT "inventory"."id" AS "inventory_id", "inventory"."value" AS ...

The npm audit command flagged an issue with an invalid tag name,

Whenever I run npm audit on a directory containing the project's package.json and package-lock.json, I encounter the following error message: 0 info it worked if it ends with ok 1 verbose cli [ '/home/user/Downloads/node-v10.14.0-linux-x64/bin/n ...

Learn how to retrieve JSON data from the Yahoo Finance REST API using Angular 2

Currently, I am in the process of developing an application that needs to fetch data from the Yahoo Finance REST API. To retrieve a table for the symbol "GOOG," I have implemented the following code: export class ActService{ act = []; url = 'http ...

Include the circle.css file in the Angular 4 project by loading it in the head section of the

I am currently working with Angular 4 and would like to incorporate the circle.css styles from cssscript. After downloading the file from the provided link, I placed the circle.css within my something component file. However, when attempting to use &l ...

ngx-loading is a fantastic addition to Angular 7, ensuring that the spinner is continually visible

While using ngx-loading to display a spinner during server response retrieval, I encountered an issue. The spinner works properly by appearing when the request is sent and disappearing once the server response is received. However, if I click on the area w ...

Exporting a Typescript class from one module and importing it into another module

I am encountering issues with my source tree structure, as outlined below: /project/ |- src/ |- moduleA |- index.ts |- classA.ts (which includes a public function called doSomething()) |- moduleB |- classB.ts Th ...

What is the best way to emphasize specific months and years in an Angular Material datepicker?

I have an array of days, which can be from any year. I am attempting to customize the Angular Material datepicker to highlight specific months and years in the selection views based on the array of days. .html <input [matDatepicker]="picker" ...

What causes an interface to lose its characteristics when a property is defined using index signatures?

Here's the code snippet I'm having trouble with, which involves tRPC and Zod. import { initTRPC, inferRouterOutputs } from '@trpc/server'; import { z } from "zod"; const t = initTRPC.create(); const { router, procedure } = t; ...

Updating the Edit icon within the Mat table is not being properly refreshed when editing inline text

I am currently working on implementing inline editing for a mat table. I found a helpful guide at this link. When I try to edit the second row on page 1 (the edit symbol icon changes), and then move to the next page without saving the changes, the second r ...

Leveraging the power of Kendo UI for Angular, bind the click event of a kendoButton to a method associated with a variable within

I have a variable called "message" in my component that is of type "any" and contains a method named "actionnowrapper()". When I bind this method to a regular HTML button like so, everything works as expected. <button (click)="message.actionnowrapper( ...

Is it possible to define data types for the global context in cucumber?

Embarking on a fresh cucumber-selenium project in Typescript, I am eager to keep the Driver in the world context. However, following the method suggested here, I encounter an issue where the Driver type remains inaccessible to step definitions. This means ...

A guide on transforming a 1-dimensional array into a 2-dimensional matrix layout using Angular

My query revolves around utilizing Template (HTML) within Angular. I am looking for a way to dynamically display an array of objects without permanently converting it. The array consists of objects. kpi: { value: string; header: string; footer: string }[] ...