Angular fails to properly handle passing HTTP GET parameters

Just delving into Angular and recently began working on an application using the OpenWeather API with a basic GET method.

Here is the code snippet from my app.component.ts file:

import { Component } from '@angular/core';
import { WeatherService } from './weather.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [WeatherService]
})
export class AppComponent {
  title = 'Ng-Weather';
  cityName: string;    
  constructor(private weather: WeatherService) { }    
  search() {
    this.weather.getWeatherbyName(this.cityName);
  }
}

The cityName variable is two-way bound. The search() function is triggered when a button is clicked, passing data to the weatherservice. Below is the content of the weather service:

import { Injectable } from '@angular/core';
import { Http, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs';
import { Weather } from './weather';
@Injectable()
export class WeatherService {
  APIurl = "http://api.openweathermap.org/data/2.5/weather";
  Appid = "xxx";
  constructor(private Http: Http) { }
  getWeatherbyName(name: string): Observable<any> {
    let myParams = new URLSearchParams();
    myParams.append('q', name);
    myParams.append('appid', this.Appid);
    return this.Http.get(this.APIurl, { search: myParams})
      .map(this.extractData)
      .catch(this.handleError);
  }
  private extractData(res: Response) {
    console.log(res.json());
    let body = res.json();
    return body.data;
  }
  private handleError(error: Response | any) {
    console.error(error.message || error);
    return Observable.throw(error.message || error);
  }
}

No errors are showing in the console or during compilation. What could be wrong? Also, how can I map the received JSON to my class and pass that instance back to the app.component?

Below is my Weather class structure:

export class Weather {
    city: String;
    max_temp: String;
    min_temp: String;
    description: String;
}

Here is a sample of the JSON response I receive:

{  
    "coord":{  
        "lon":80.28,
        "lat":13.09
    },
    "weather":[  
        {  
            "id":803,
            "main":"Clouds",
            "description":"broken clouds",
            "icon":"04n"
        }
    ],
    "base":"stations",
    "main":{  
        "temp":304.15,
        "pressure":1008,
        "humidity":79,
        "temp_min":304.15,
        "temp_max":304.15
    },
    "visibility":6000,
    "wind":{  
        "speed":3.1,
        "deg":160
    },
    "clouds":{  
        "all":75
    },
    "dt":1504629000,
    "sys":{  
        "type":1,
        "id":7834,
        "message":0.0029,
        "country":"IN",
        "sunrise":1504571272,
        "sunset":1504615599
    },
    "id":1264527,
    "name":"Chennai",
    "cod":200
}

I only need specific data from this JSON response rather than the entire payload.

Answer №1

The main issue you are facing is not subscribing to the observable created by your getWeatherbyName function. Observables returned by Http are considered cold, meaning they only start emitting values when subscribed to:

Cold observables begin emitting values once subscribed, while hot observables like mouse move events or stock tickers already emit values without an active subscription.

To subscribe to this observable, update your search function as follows:

search() {
    this.weather.getWeatherbyName(this.cityName)
        .subscribe();
}

This alone won't completely solve your issue - You'll need to handle the subscription response, like assigning the received data to component properties for UI rendering.

You may have other problems in your project, so feel free to ask separate questions on a platform like Stack Overflow or use a search engine for assistance.

Answer №2

To enhance the http get method, consider utilizing a RequestOptions object:

import { RequestOptions } from '@angular/http';    

getWeatherInfo(name: string): Observable<any> {
            let myParams = new URLSearchParams();
            myParams.append('q', name);
            myParams.append('appid', this.Appid);

            let options = new RequestOptions({ search: myParams}); //<----- UPDATED

            // Example of how the http request should be structured: http://api.openweathermap.org/data/2.5/weather?appid=xxx&q=Chennai
            return this.Http.get(this.APIurl, options) //<<----- UPDATED
              .map(this.extractData)
              .catch(this.handleError);
          }

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

Error Message: In Android programming, a value of type java.lang.String cannot be converted to JSONObject

Looking for help with creating a login page on Android activity that connects to a database. Running into the error message "org.json.JSONException: Value New to Android programming and have been troubleshooting for three days now. Any assistance is appre ...

Enhancing User Authentication: Vue 3 with TypeScript Login

Recently, I came across a new technology called Supabase and noticed that most resources mention registration on JavaScript instead of TypeScript. As I started working on a project using Vue 3 + TypeScript, I encountered some errors that I need help resolv ...

Exploring the power of Django's JSONField in combination with Tastypie

I am working with a MySQL table that uses the JSONField type in Django. This is how my model is structured: from django.db import models from json_field import JSONField class Model(models.Model): obj = JSONField() When I send a value via Tastypi ...

Typescript implements strict enforcement of partial interfaces

In my application, I am working with JSON data. Here is a simplified example: data { prop1: "abc", prop2: 123, COL_A12: "mydata", COL_A13: "myotherdata", } I am aware that the data will consist of multiple prop1 and prop2 properties. However, CO ...

What could be causing my cmd to report an error stating that it is unable to locate the node-modules

https://i.sstatic.net/4ztfB.png Take a look at my command prompt below. Do I need to keep the module folder and the code folder in the same directory? ...

What is the best method for transforming a JSON object into a neatly formatted JSON string?

After storing the output of cat ~/path/to/file/blah | jq tojson in a variable for later use in a curl POST with JSON content, I noticed that all line breaks were removed. While I understand that line breaks are not supported in JSON, is there a way to repl ...

Calculate the frequency of a specific name within a Json Array

I am looking to calculate the frequency of occurrences in a JSON Array returned by an API. Here is my data: data = [ {"id":"1939317721","pauseReason":"DISPLAY","DeptName":"Account"}, {"id":"1939317722","pauseReason":"DISPLAY","DeptName":"Admission"}, ...

How can I make a Java API request using JsonReader?

Having trouble figuring this out: I need to call the openweather api in java and display the result on the console. Can't seem to find any helpful tutorials, they all focus on parsing JSON from a file... Not sure if I'm on the right track? Tryin ...

Unable to Identify Actual Type from Global Declaration within TypeScript Project References

For the purpose of demonstrating my issue, I have set up a demo repository. This repository comprises two projects: electron and src, both utilizing TypeScript project references. In the file src/global.d.ts, I have defined the type API_TYPE by importing ...

Guide to deserializing a collection of interfaces within a child element

My ASP.NET MVC2 application features a complex object structure as outlined below: public class IDealer { string Name { get; set; } List<IVehicle> Vehicles { get; set; } } public class DealerImpl { public string Name { get; set; } public Li ...

How to effectively manage missing values in jq using if-then-else-end statements

Below is the command I utilize to extract the necessary information: .results | .[] | {id, name: .general.name, platform: .general.platform, site: .general.site.name, ea_site: .extensionAttributes.[] | select(.definitionId=="57").values.[]} If . ...

The error message "external.js: $ is not defined" indicates that

Recently, I integrated an external JavaScript file into my Angular 14 project. This JS file contains the event $('.class').click(). However, every time I launch the application on localhost, a message pops up in the browser stating that $ is not ...

Crop the contents of an array between two specified characters

Looking to extract individual values from an array like this: "Names": [ "Name[name]", "Result[Type]", "Validation[Option]", "Status[Pointer]" ] The desired output should be: "Names": [ "name", "Type", "Option", ...

Having trouble with an error on Amazon S3 that says "ETagMissing: No access to ETag property on response"? Make sure to review the CORS configuration to expose the ETag header for a solution

Encountering an error message stating "ETagMissing: No access to ETag property on response. Check CORS configuration to expose ETag header." while attempting a multipart upload to AWS. Despite thorough research online, I have been unable to find a solution ...

Using Node.js to insert JSON data into a MySQL table

In my database, I have a table called users with the following fields: id, name (varchar), and gallery (json). The gallery field contains the image paths of user-uploaded rows. Users can add more images to their gallery, and each image path is stored in ...

Invalid JSON due to escaped HTML characters

After using a tool to escape all characters in my JSON containing HTML code, I encountered an issue when trying to validate it. The error message received was: Parse error on line 2: { "html": "<table class=\"MsoT -----------^ Expecting &apos ...

Store the fetched data as JSON in the local storage

Struggling to find a solution after reading several articles, I am working on fetching a large JSON from an API and I want to cache the response in the localStorage. The goal is for the script to check for an object with the requested ID in the cached JSON ...

Text hidden within Android fragment

Note: The JSON data is not parsed in the CardView. Main Fragment I implemented a fragment to display data on every item click using a slider menu. I wrote code to parse JSON data using Retrofit web service. public class Physical_Geography_Activity exten ...

Why are my animation states being shared among different instances of the component?

Why is the animation playing for both instances of the carousel component when interacting with just one call (e.g. clicking next or prev)? carousel.component.ts @Component({ selector: 'app-carousel', standalone: true, templateUrl: './c ...

Angular's GET request response is returning an "Undefined" value instead of the

As an Angular beginner, I've successfully set up and tested a service that retrieves data from a JSON file using the Get method. However, when attempting to access the data inside the JSON file, it returns as undefined. My goal is to use this data as ...