1b - Brief Introduction To Angular

In this section we will use angular services and review observables with RxJS

1. Add a user service

ng g service services/user/user

2. Add HttpClientModule to AppModule

src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { HttpClientModule } from '@angular/common/http'; // Added

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

3. Make a User service

Add some fake data in a user.json file in the assets folder of your new app. This is in place of a URL to hit a real API, for no.

Make the service and inject in the HttpClient

4. Add a UserList component and inject in the User service

Make a user-list component, 'c' is short hand for component.

Add a new eagerly loaded route for the UserList component

Check the route works by navigating to http://localhost:4200/user-list

Here we do the simple async pipe We will stop and discuss observables and their operators in slides here https://docs.google.com/presentation/d/1xf8aPIvQjgjUVGH_1sRkikvh5H73x2xvX7PnN4AjYt4/edit?usp=sharing

Inject user service and call its getUsers method and bind in to a local variable

The below is an example of subscribing in the component. Try it out but we will be using the async pipe. We bind to the observable in the rest of the demo so make sure to change back.

Use the async pipe to and an ngFor template directive to subscribe and iterate over the users.

5. Use Angular ngFor to bind users

6. Add strong typing

Add User type to a models folder

Add User type to the service

Add User type to the UserList component

Extra reading

Naming observables - https://medium.com/@benlesh/observables-are-just-functions-but-also-collections-how-do-i-name-them-918c5ce2f64

Last updated