nx/docs/angular/tutorial/04-connect-to-api.md
Brandon eef0db73bf
docs(core): cleanup tutorials (#6268)
* docs(core): cleanup tutorials

* chore: review fix

Co-authored-by: Isaac Mann <isaacplmann@users.noreply.github.com>

Co-authored-by: Isaac Mann <isaacplmann@users.noreply.github.com>
2021-07-06 13:07:59 -04:00

1.5 KiB
Raw Blame History

Angular Nx Tutorial - Step 4: Connect to an API

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

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

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

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

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

interface Todo {
  title: string;
}

@Component({
  selector: 'myorg-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  todos: Todo[] = [];

  constructor(private http: HttpClient) {
    this.fetch();
  }

  fetch() {
    this.http.get<Todo[]>('/api/todos').subscribe((t) => (this.todos = t));
  }

  addTodo() {
    this.http.post('/api/addTodo', {}).subscribe(() => {
      this.fetch();
    });
  }
}