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

I encountered difficulty in testing the Angular Material Select Component due to complications with the CDK Test Harness

While working on testing a component that utilizes Angular Material Components, I came across the CDK Test Harness and decided to use it to retrieve the count of options in the Mat Select component. You can find more information about the CDK Test Harness ...

Angular2: Navigational Errors Demystified

After updating the angular packages from version 2.4.10 to 4.0.0, I encountered the following errors when navigating: ERROR Error: Uncaught (in promise): Error: Found the synthetic property @transformPlaceholder. Please include either "BrowserAnimationsMo ...

How can certain properties be mandated while still permitting additional ones?

I am currently working on creating a function that requires one property as an argument, but could potentially have additional properties as well. Here is an example: interface Foo { bar: string; } function someFunc(obj) { // implement functional ...

Modifying Views on the Fly with Ionic 2

When the toggle button on the page is clicked, the current page view will switch to a different HTML layout. I attempted to modify @Page, but after it loads once, I am unable to change it again. @Page({ templateUrl: isTrue ? 'build/pages/detail/ ...

"Implementing an Angular route component that adjusts based on specific

I am currently working on routing within my application for the 'feed' module. Within this feed, there are two types of posts that I need to display with a direct link to show full information. How can I ensure that the right component is opened ...

Exploring angular2 nested routes and their construction using routerLink

I have been working on implementing a nested nested route structure where I have tabs within tabs using dynamic loading with the Angular 2 material tab component. The first nested tab works as expected, however, I am facing issues with the second nested t ...

Discover the steps to create a virtual scroll dropdown menu with Kendo in Angular

I'm dealing with a large data set obtained from an API. Instead of displaying all the data in the dropdown initially, I'd like to fetch the results from the server API as the user scrolls down through the dropdown menu. Could someone please prov ...

Is there a way to identify the specific button that was clicked within an Angular Material dialog?

import {Component, Inject} from '@angular/core'; import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material'; /** * @title Dialog Overview Example with Angular Material */ @Component({ selector: 'dialog-overview-ex ...

Ways to receive real-time notifications upon any modifications in my cloud firestore database?

I am currently in the process of developing a chat application using Angular and Firebase Cloud Firestore. My goal is to have a counter on the client side that updates whenever any document in the 'groups' collection is updated. Within my clien ...

Ways to utilize and display data in a *ngFor loop

I have created a simple service for accessing an HTTP service. Can anyone help me with how to bind this service information in *ngFor? import { Component } from '@angular/core'; import {Http } from '@angular/http'; import { In ...

Transmitting a base64 data URL through the Next.js API route has proven to be a challenge, but fortunately, other forms of

It's frustrating me to no end. I've successfully done this before without any problems, but now it just won't cooperate. Everything works fine when passing an empty array, a string, or a number. However, as soon as I include the data URL, t ...

Loop through object properties with *ngFor

Seeking suggestions on how to iterate over object keys in HTML using *ngFor within Angular 12. The provided data structure is as follows: { "data": [ { "student1": { "name": "Jhon", &quo ...

Tips for avoiding the push method from replacing my items within an array?

Currently, I am diving into Typescript and VueJS, where I encountered an issue with pushing elements to my array. It seems to constantly override the 'name' property. Let me share the code snippet causing this problem: const itemsSelectedOptions ...

Animate in Angular using transform without requiring absolute positioning after the animation is completed

Attempting to incorporate some fancy animations into my project, but running into layout issues when using position: absolute for the animation with transform. export function SlideLeft() { return trigger('slideLeft', [ state('void&a ...

Implementation of Asp.Net core identity combined with Angular 2

Recently, I developed a web-app using Asp.Net with angular2. To kickstart the project, I utilized generator-aspnetcore-spa. Now, my next step is to integrate identity management into the application. After some consideration, I have decided to go with Asp ...

Error: npm encountered a loop error while attempting to download

Looking to implement Google login, I attempted the following command: npm install --save angularx-social-login. Unfortunately, it returned an error: D:\proj>npm install --save angularx-social-login npm ERR! code ELOOP npm ERR! syscall open npm ERR ...

How can you utilize both defineProps with TypeScript and set default values in Vue 3 setup? (Typescript)

Is there a way to use TypeScript types and default values in the "defineProps" function? I'm having difficulty getting it to work. Code snippet: const props = defineProps<{ type?: string color?: 'color-primary' | 'color-danger&a ...

typescript undefined subscription to observable

After making an http request to fetch some data, I am facing issues in displaying it as intended. The dropdown select for entriesPerPage, and the left and right cursors for switching page in pagination are working fine. However, upon switching a page, I en ...

Unexpected runtime error when using Prisma with NodeJS and Express

While starting the server, I encounter an error message saying [ERROR] 14:48:46 Error: Cannot find module './runtime/library'. The stack trace points to the directory named prisma. Even after executing npx prisma generate, the directory called p ...

Turf.js - Missing type declarations when importing into a Vue/Vite environment

Struggling with Turf.js's bbox functionality. Despite all my efforts, TypeScript type definitions remain elusive. I attempted the following steps: Included in package.json: "dependencies": { ... "@turf/turf": "6.5.0&q ...