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/user2. Add HttpClientModule to AppModule
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
Inject user service and call its getUsers method and bind in to a local variable
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