Angular Tutorial – Part 2
A143MKAngular Tutorial – Part 2: Build Production-Ready Apps
Continue learning Angular with RxJS, route guards, HTTP interceptors, testing, performance, security and deployment.
1RxJS and Observables
Angular's HttpClient returns Observables. An Observable represents values that arrive over time. Use operators such as map to transform values and switchMap when a new search should replace an older request.
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError, of } from 'rxjs';
@Component({
selector: 'app-users',
standalone: true,
template: `
@if (error) {
<p>{{ error }}</p>
}
@for (user of (users$ | async) ?? []; track user.name) {
<p>{{ user.name }}</p>
}
`
})
export class UsersComponent {
private http = inject(HttpClient);
error = '';
users$ = this.http.get<{ name: string }[]>('/api/users').pipe(
catchError(() => {
this.error = 'Could not load users. Please try again.';
return of([]);
})
);
}async pipe in templates: Angular subscribes and cleans up for you.2Route Guards and Resolvers
A guard can decide whether navigation is allowed. Return a redirect tree instead of navigating as a side effect. A resolver can load required data before a route is activated.
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const signedInGuard: CanActivateFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.isSignedIn()
? true
: router.createUrlTree(['/login']);
};{
path: 'account',
canActivate: [signedInGuard],
loadComponent: () => import('./account.component')
.then(m => m.AccountComponent)
}3HTTP Interceptors
Functional interceptors are a central place to add common request behavior, such as attaching an access token. Clone requests because Angular HTTP requests are immutable.
import { inject } from '@angular/core';
import { HttpInterceptorFn } from '@angular/common/http';
import { AuthService } from './auth.service';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).accessToken();
if (!token) return next(req);
const authorized = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next(authorized);
};import { provideHttpClient, withInterceptors } from '@angular/common/http';
providers: [
provideHttpClient(withInterceptors([authInterceptor]))
]4Shared State with Signals
For simple shared state, a root-provided service with a private writable signal and a read-only public signal keeps updates controlled.
import { Injectable, computed, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CartStore {
private itemsState = signal<string[]>([]);
items = this.itemsState.asReadonly();
itemCount = computed(() => this.itemsState().length);
add(item: string) {
this.itemsState.update(items => [...items, item]);
}
clear() {
this.itemsState.set([]);
}
}Use a dedicated state library when your app needs more complex workflows, data caching or debugging tools; choose the smallest approach that fits.
5Testing Components and Services
Tests help verify user-visible behavior. This example checks that a component renders its heading using Angular's test utilities.
import { TestBed } from '@angular/core/testing';
import { GreetingComponent } from './greeting.component';
describe('GreetingComponent', () => {
it('shows the greeting', async () => {
await TestBed.configureTestingModule({
imports: [GreetingComponent]
}).compileComponents();
const fixture = TestBed.createComponent(GreetingComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Hello');
});
});For HTTP services, use Angular's provideHttpClientTesting() and HttpTestingController to assert requests without calling a real API.
6Performance and Lazy Loading
Load route code only when needed, and defer non-critical UI. These features can reduce the initial JavaScript users need to download.
{
path: 'reports',
loadComponent: () => import('./reports.component')
.then(m => m.ReportsComponent)
}@defer {
<app-analytics-chart />
} @placeholder {
<p>Chart will load when needed.</p>
} @loading (minimum 300ms) {
<p>Loading chart...</p>
}Also use pagination for large lists, track items in repeated views, and measure real performance before optimizing.
7Security and Accessibility
- Keep authorization checks on the server; never rely only on client-side route guards.
- Do not put secrets or private API keys in frontend code or public environment files.
- Avoid bypassing Angular's built-in HTML sanitization for untrusted content.
- Use semantic HTML, labels for form controls, visible keyboard focus and descriptive button text.
- Show validation errors in text and associate them with the relevant form field.
8Build and Deployment
Before publishing, create and test a production build:
ng build
ng testDeploy the generated browser output to your hosting provider, configure the web server to serve the app entry point for client-side routes, and use HTTPS. Configure server-side credentials outside the frontend bundle.
🎉 You have completed Angular Tutorial Part 2. Keep building small features, test them, and consult the official Angular documentation as the framework evolves. — A143MK
No comments :
Post a Comment
Please Write a Message for Programming or something else 🙏