Skip to main content

ASP.NET Core & Angular 2 - Chapter 3 Display the weather

Display the weather

We’ll take a look at how to create a .NET Core Web API controller, retrieve data from it and pass that up to the Angular front end (where it will be rendered as a page on your site).

Add Controller Method

We’ll initially just add a simple method to the WeatherController to make use of the OpenWeather API to get forecast by City.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 26 27 28 29 30 31 32
[HttpGet("[action]/{city}")] public async Task WeatherForecast(string city) { using (var client = new HttpClient()) { try { client.BaseAddress = new Uri("http://api.openweathermap.org"); var response = await client.GetAsync($"/data/2.5/weather?q={city}&appid=[Insert API Key Here ]&units=metric"); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsStringAsync(); var openWeather = JsonConvert.DeserializeObject(result);
var forecast = new { Temp = openWeather.Main.Temp, Summary = string.Join(",", openWeather.Weather.Select(x => x.Main)), City = openWeather.Name }; return Ok(forecast); } catch (HttpRequestException httpRequestException) { return BadRequest($"Error getting weather from OpenWeather: {httpRequestException.Message}"); } }
}

I created some Custom Classes to be used to capture the results

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 public class Description {     public string Main { get; set; } public string Condition { get; set; } } public class Main { public string Temp { get; set; } } public class WeatherResponse { public string Name { get; set; } public IEnumerable Weather { get; set; } public Main Main { get; set; } }

Angular 2 Components

We’ll create a sime very simple Angular 2 Components in order to illustrate how they will all work together to retrieve data, and how they can be further developed to provide more abstraction.

We’ll create a Angular Service to interact with out .net API.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 26 27 28 29 30 31 32
 // Interface Declaration import { Observable } from 'rxjs/Observable'; import { Response } from '@angular/http'; export interface IWeatherService { getWeatherReport(city : string): Observable; } /////////////////////////////////////////////////////////// // Class Declaration import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import {Observable } from 'rxjs/Observable'; import {IWeatherService } from './weatherservice.interface'; @Injectable() export class WeatherService implements IWeatherService{ constructor(public http : Http){ } getWeatherReport(city : string): Observable{ var url :string = '/api/Weather/WeatherForecast/' + city; return this.http.get(url); } }


We’ll create a very simple class that will interact with the service to get the desired forecast and make it available to the UI to present.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 26 27 28 29 30 31 32
import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { WeatherService } from '../../../services/weather.service'; import { Forecast } from '../../models/forecast.model'; @Component({ selector: 'weather', templateUrl: './weather.component.html' }) export class WeatherComponent implements OnInit {
public forecasts: Forecast; constructor(private service : WeatherService) { } ngOnInit(): void{ // In future we will add a method here to determine users default city // for now we will just set it to hometown this.getWeatherReport('Swindon'); } getWeatherReport(city : string){ this.service.getWeatherReport(city).subscribe(result => { this.forecasts = result.json() as Forecast; }); } }
We’ll create a very simple UI presentation class to present the data

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 <h1>Weather forecast</h1> <p>This component demonstrates fetching data from the server.</p> <p *ngIf="!forecasts"><em>Loading...</em></p> <table class='table' *ngIf="forecasts"> <thead> <tr> <th>City</th> <th>Temp. (C)</th> <th>Summary</th> </tr> </thead> <tbody> <tr> <td>{{ forecasts.city }}</td> <td>{{ forecasts.temp }}</td> <td>{{ forecasts.summary }}</td> </tr> </tbody> </table>

Comments

Popular posts from this blog

ASP.NET Core & Angular 2 - Chapter 2 Routing

Route to a component The Angular 2 router is a powerful tool which enables you to do just that. Specifically you can configure it to route to a component when the user enters a specific url for your site. So in this case, we could configure it so that navigating to http://domain/hello routes directly to the hello world component. Open up your app.module.ts file and make the following simple change in routing section. 1 2 3 4 5 6 7 8 9 10 11 imports: [      DefaultModules, //This automatically imports BrowserModule, HttpModule, and JsonpModule too.      RouterModule.forRoot([          { path: '' , redirectTo: 'home' , pathMatch: 'full' },          { path: 'home' , component: HomeComponent },          { path: 'counter' , component: CounterComponent },       ...

ASP.NET 4.0 with Ajax

It's common for an web application to retrieve data from server and bind to control. Control being alone without data binding is nothing more than styled modeling statue. So interacting between DB and web control comes to challenge for developers whenever we design its working procedure. Ajax is possible only with a strong JavaScript engine that runs within the client browser and provides the foundation for more advanced and asynchronous features. The Javascript library currently incorporated in ASP.NET 3.5 Service Pack 1 is a necessary, but insufficient, attempt to deliver such a library. A more powerfule ASP.NET AJAX platform is required and it is just being introduced as part of ASP.NET AJAX 4.0 Requirements for Client-Side Data Binding There are two fundamental patterns for implementing data binding functionalities. One is the HTML Message pattern, and the other is the Browser-side Template pattern. The former entails making a remote service call to a component that re...