Angular Nx Tutorial - Step 4: Connect to an API

Nx.dev Tutorial | Angular | Step 4: Connect to API

Real-world applications do not live in isolation — they need APIs to talk to. Setup your app to talk to an API.

Open apps/todos/src/app/app.module.ts to import HttpClientModule.

1import { BrowserModule } from '@angular/platform-browser';
2import { NgModule } from '@angular/core';
3
4import { AppComponent } from './app.component';
5import { HttpClientModule } from '@angular/common/http';
6
7@NgModule({
8  declarations: [AppComponent],
9  imports: [BrowserModule, HttpClientModule],
10  providers: [],
11  bootstrap: [AppComponent],
12})
13export class AppModule {}

Now, use HttpClient in the component to get the data from the api.

1import { Component } from '@angular/core';
2import { HttpClient } from '@angular/common/http';
3
4interface Todo {
5  title: string;
6}
7
8@Component({
9  selector: 'myorg-root',
10  templateUrl: './app.component.html',
11  styleUrls: ['./app.component.css'],
12})
13export class AppComponent {
14  todos: Todo[] = [];
15
16  constructor(private http: HttpClient) {
17    this.fetch();
18  }
19
20  fetch() {
21    this.http.get<Todo[]>('/api/todos').subscribe((t) => (this.todos = t));
22  }
23
24  addTodo() {
25    this.http.post('/api/addTodo', {}).subscribe(() => {
26      this.fetch();
27    });
28  }
29}