Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 74 ยท Projects

Project: Weather Dashboard with HttpClient

Build an Angular weather dashboard in four steps - a typed service, loading and error states with resource(), and a debounced city search. Real code plus runnable fake-API stand-ins.

A weather dashboard is a small project with a very typical shape: the user types something, the app asks a server a question, and the screen has to show three honest states while it waits: loading, error and result. Almost every data-driven Angular screen, from product search to user profiles, is a variation of this loop.

We will design it in four steps: a typed API service, a component that turns the request into signals, a debounced search box, and a clear plan for loading, empty and error states. You will use ideas from HttpClient: Requests and Responses, linkedSignal, resource and httpResource and Signals and RxJS Interop. If one of them feels shaky, skim it first.

Real versus stand-in. The typescript and html blocks are real Angular code and are read-only, because this site cannot run the Angular compiler or call a real weather server. The runnable examples re-implement the logic (the service rules, the debounce and the cancellation) with a fake API made of timers. Everything they print is deterministic. The endpoint /api/forecast in the real code is an invented example endpoint: point it at whatever weather API you use.

The plan

Here is the architecture. Notice that the component never talks to the network: only the service does.

flowchart LR
  Box["Search box<br/>(query signal)"] --> Deb["Debounce<br/>+ distinct"]
  Deb --> Res["resource()<br/>params = city"]
  Res --> Svc["WeatherService<br/>(HttpClient)"]
  Svc --> API[("Weather API")]
  Res --> View["Template:<br/>loading / error / result"]

The query flows through a debounce into a resource; the resource calls the service; the template reads the resource's signals.

The files of the real app:

TEXT
src/app/
  weather/
    forecast.ts              (types)
    weather.service.ts       (HTTP only)
    weather-dashboard.ts     (component)

Step 1: types and a service that does only HTTP

Start with the data. A TypeScript interface describes what you expect the server to send, so the rest of the app is checked against it.

TypeScript
// forecast.ts
export type Condition = 'sunny' | 'cloudy' | 'rain';

export interface Forecast {
  city: string;
  temperatureC: number;
  condition: Condition;
  hourly: number[];
}

The service is the only place that knows the URL, the query parameters and the error rules. It is providedIn: 'root', so one instance serves the whole app (see Services and Dependency Injection).

TypeScript
// weather.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { Forecast } from './forecast';

@Injectable({ providedIn: 'root' })
export class WeatherService {
  private readonly http = inject(HttpClient);

  forecast(city: string): Observable<Forecast> {
    return this.http.get<Forecast>('/api/forecast', { params: { city } });
  }
}

The app config must call provideHttpClient() once, usually with withFetch() as covered in the HttpClient lesson. Two details matter here. First, params: { city } lets Angular encode the value, so a city like Sรฃo Paulo or Rio & Co cannot break the URL. Second, get<Forecast> is a promise, not a check: TypeScript trusts you, and nothing verifies at runtime that the server really sent a temperatureC number. For an API you do not control, validate the shape (with a hand-written guard or a schema library) before handing data to the UI.

The first runnable example models exactly this layer against a fake server: typed result, runtime shape check, a retry for temporary server failures (status 5xx) and friendly messages for errors.

TypeScript A typed weather service with validation and retry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Each city shows one rule. London works straight away. Flaky fails once, the service retries quietly and succeeds. Atlantis gets a 404 and becomes a human message, not a status code. Glitch returns HTTP 200 but with a wrong shape, which only the runtime check catches. The service decides what went wrong; the component will decide how to show it.

Step 2: a component driven by one resource

The component needs one source of truth: the city the user wants. Everything else (the request, the loading state, the error) is derived from it.

TypeScript
// weather-dashboard.ts
import { Component, inject, resource, signal } from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { WeatherService } from './weather.service';

@Component({
  selector: 'app-weather-dashboard',
  templateUrl: './weather-dashboard.html',
})
export class WeatherDashboard {
  private readonly weather = inject(WeatherService);

  readonly city = signal('');

  readonly forecast = resource({
    params: () => {
      const name = this.city().trim();
      return name ? { name } : undefined;
    },
    loader: ({ params }) => firstValueFrom(this.weather.forecast(params.name)),
  });
}

Returning undefined from params keeps the resource idle when the box is empty, so no request is sent for nothing. firstValueFrom turns the service's Observable into the Promise a resource loader needs. This keeps the service reusable with RxJS operators elsewhere. If you prefer to stay in Observable land, Angular also offers rxResource in @angular/core/rxjs-interop, which takes an Observable-returning function instead; check the current API reference for the exact option names, because this area is young. One more option is httpResource, which would replace both the service call and the loader with a URL function; the service version is better when several screens share request rules such as retries.

Step 3: show the three states honestly

The template reads the resource's signals. Handle every state on purpose, in this order: nothing asked, loading, error, result.

HTML
<label for="city">City</label>
<input id="city" type="search" [value]="city()" (input)="city.set($any($event.target).value)" />

@if (forecast.status() === 'idle') {
  <p>Type a city to see its forecast.</p>
} @else if (forecast.status() === 'loading') {
  <p role="status">Loading...</p>
} @else if (forecast.error()) {
  <p role="alert">We could not load that forecast.
    <button (click)="forecast.reload()">Try again</button>
  </p>
} @else if (forecast.hasValue()) {
  @let f = forecast.value()!;
  <h2>{{ f.city }}</h2>
  <p>{{ f.temperatureC }} &deg;C, {{ f.condition }}</p>
  <ul>
    @for (t of f.hourly; track $index) {
      <li>{{ t }} &deg;C</li>
    }
  </ul>
}

Notes on the choices. role="status" and role="alert" make screen readers announce the loading and error messages. reload() lets the user retry without retyping. The idle branch stops the page from looking broken when it is empty. $any($event.target) is a shortcut for brevity; in a real app, prefer a template reference variable such as #box and box.value, as covered in Event Binding and $event. The hourly values use track $index because they have no identity of their own, see Control Flow.

With the code above, every keystroke changes city and starts a request: typing "London" would send six. Debouncing waits until the user pauses. The Angular way is to bridge to RxJS for time-based logic, then back into a signal:

TypeScript
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, map } from 'rxjs';

readonly query = signal('');

private readonly settledQuery = toSignal(
  toObservable(this.query).pipe(
    map(text => text.trim()),
    debounceTime(300),
    distinctUntilChanged(),
  ),
  { initialValue: '' },
);

readonly forecast = resource({
  params: () => {
    const name = this.settledQuery();
    return name ? { name } : undefined;
  },
  loader: ({ params }) => firstValueFrom(this.weather.forecast(params.name)),
});

query holds what the user typed and updates on every key. settledQuery only changes after 300 ms of silence, and distinctUntilChanged ignores a change that results in the same trimmed text, such as adding a trailing space. The resource watches settledQuery. Compare with RxJS Operators You Need: debounceTime and distinctUntilChanged are the two operators of this lesson. The resource itself also cancels the loader's previous run when params change, so a slow answer for "London" cannot replace the newer answer for "Paris". In this version, the cancellation reaches the HTTP request only if you wire the abort signal through; the result of the old load is ignored in any case.

The second runnable example is a stand-in for steps 3 and 4 together: a debounce, a "same as last time" filter, a state machine for idle, loading, ready and error, and cancellation of outdated requests.

TypeScript Debounced search with loading, error and cancellation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read the output from top to bottom. Six keystrokes produce a single "Loading London..." line, because the debounce swallowed the intermediate texts. When the user switches to Paris while London is slow, the London request is cancelled and Paris is the only result that reaches the screen. The trailing space produces no output at all. Oslo shows the error state, and clearing the box returns to idle.

Where to go from here

  • Show a skeleton instead of "Loading...", or keep the previous forecast on screen while the next one loads (reloading status).
  • Cache recent cities in the service with a Map, and show them as quick buttons.
  • Add a unit toggle (C or F) as a computed() over the temperature. Never store both values.
  • Write tests with HttpTestingController, see Testing Components and Services.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the project put all HTTP calls in WeatherService instead of in the component?

    Components can inject HttpClient, but keeping requests in a service gives one place for URL and error handling and makes the component easy to test with a fake service.
  2. 2. What does http.get<Forecast>(url) guarantee at runtime?

    Generics are erased at runtime. If you do not control the API, validate the shape yourself before using the data.
  3. 3. What does returning undefined from the params function of a resource do?

    An undefined params value means there is nothing to load yet, which is perfect for an empty search box.
  4. 4. What is the job of distinctUntilChanged in the debounced search?

    After the text is trimmed, an unchanged value would trigger an identical request. distinctUntilChanged drops it.
  5. 5. Why show the loading, error and idle states as separate branches?

    Each state tells the user what is happening. Handling them on purpose, with roles for screen readers, is what makes data screens feel reliable.

Summary

  • Keep HTTP in a service with typed methods; the component owns state and display.
  • A resource() with a params function turns the search text into loading, error and value signals, and stays idle while params is undefined.
  • Bridge signals to RxJS with toObservable, apply debounceTime and distinctUntilChanged, then return with toSignal.
  • Cancel or ignore outdated requests so slow answers cannot overwrite newer ones.
  • Validate data from servers you do not control: the generic type on get<T>() is not a runtime check.
  • Handle idle, loading, error and result explicitly in the template, with role attributes for screen readers.

Next: Project: Shopping Cart and Checkout.