The Full Stack Guide: Connecting Angular with .NET
Bridging the frontend and backend for a seamless application
The combination of Angular on the frontend and ASP.NET Core on the backend is a classic enterprise stack. It offers type safety across the board (TypeScript & C#), high performance, and robust tooling. But how do you connect them effectively beyond a simple "Hello World"?
In this guide, we will walk through the full lifecycle: Authentication, CRUD operations, and Handling Errors gracefully.
1. Secure Communication: JWT Authentication
Stateful sessions are out; Stateless Tokens are in. JSON Web Tokens (JWT) are the standard for securing Single Page Applications (SPAs).
The Handshake: Login once, access everywhere.
The Interceptor Pattern
Instead of manually adding the `Authorization` header to every single HTTP request, use an Angular Interceptor to attach the token automatically.
// auth.interceptor.ts
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = localStorage.getItem('auth_token');
if (token) {
const cloned = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next(cloned);
}
return next(req);
};
2. Sending Data: The POST Request
Fetching data is easy, but sending it requires validation. Here is how to handle a form submission with error handling.
// product.service.ts
createProduct(product: Product): Observable<Product> {
return this.http.post<Product>(this.apiUrl, product).pipe(
catchError(this.handleError)
);
}
On the backend, your Controller action returns a CreatedAtAction result to follow REST
standards:
// ProductsController.cs
[HttpPost]
public async Task<ActionResult<Product>> Create(ProductDto dto) {
var product = await _service.AddAsync(dto);
return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}
Step 3: Global Error Handling
When the backend explodes, the frontend shouldn't freeze. You need a centralized way to catch errors and show notifications.
Graceful Degradation: Turning crashes into user-friendly alerts.
// error.interceptor.ts
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
const toastService = inject(ToastService);
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
toastService.error('Session expired. Please login again.');
} else {
toastService.error('Something went wrong. Try again later.');
}
return throwError(() => error);
})
);
};
Conclusion
Connecting Angular and .NET is about more than just fetching JSON. By implementing Interceptors for Auth and Errors, and following REST standards for CRUD, you build a robust "Full Stack" ecosystem that is secure and scalable.
No comments:
Post a Comment