0

I am working on a weather application on Angular 4 and i got the data from an API. This is my code for the searvice that fetches the data from the API

import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
@Injectable()

export class WeatherService{
    constructor(private http: Http){}

    getWeather(location){
    return(this.http.get(`http://api.openweathermap.org/data/2.5`/weather?q=${location}&APPID=XXXXXXXXXXXXXXXXXXXXX`));
   }
}

And in another component am requesting for the data:

import { Component, OnInit } from '@angular/core';
import { WeatherService } from "../shared/services/weather.service";
import "rxjs/add/operator/map";
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
  private weatherdata;
  constructor(private weatherService: WeatherService) { }
  city = "";
  ngOnInit() {
  }

  getWeather():void{
    this.weatherService.getWeather(this.city)
    .map((data) => data["_body"])
    .subscribe((data) => this.weatherdata = data);
  }
}

I see all the data when i try to console.log the data in the subscribe() function as:

{"coord":{"lon":3.4,"lat":6.45},"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"base":"stations","main":{"temp":297.883,"pressure":1023.84,"humidity":100,"temp_min":297.883,"temp_max":297.883,"sea_level":1028.6,"grnd_level":1023.84},"wind":{"speed":4.16,"deg":240.504},"rain":{"3h":3.935},"clouds":{"all":92},"dt":1501330679,"sys":{"message":0.0021,"country":"NG","sunrise":1501306837,"sunset":1501351501},"id":2332459,"name":"Lagos","cod":200}

, but when i try interpolating {{weatherdata.name}} in my HTML its empty, anything am doing wrong here?

3
  • What do you expect to get with {{weathername.data}} ? I don't see anything like that in your response? Nor that you would have a variable named weathername? Commented Jul 29, 2017 at 12:41
  • Am sorry, i meant {{weatherdata.name}} Commented Jul 29, 2017 at 12:43
  • I expected it to be "London" Commented Jul 29, 2017 at 12:43

1 Answer 1

2

What you are doing now, you are getting the string value of your response when you get data like so:

.map((data) => data["_body"])

You want the JSON instead:

.map((data) => data.json())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.