Roadmap › Angular (2 → 21) › Module: Getting Started
Lessons in this course (16)
5. Connecting Angular to SQL Server (through an ASP.NET Core API)
Intermediate★ Must knowLesson 5 of 16
The usual enterprise stack: Angular → ASP.NET Core Web API → EF Core/Dapper → SQL Server.
csharp
// ASP.NET Core API — ProductsController.cs (EF Core)
[ApiController, Route("api/[controller]")]
public class ProductsController(ShopDbContext db) : ControllerBase
{
[HttpGet]
public async Task<IEnumerable<ProductDto>> Get(CancellationToken ct) =>
await db.Products.AsNoTracking().OrderBy(p => p.Name).Select(p => new ProductDto(p.Id, p.Name, p.Price)).ToListAsync(ct);
}
// Program.cs: builder.Services.AddDbContext<ShopDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));
// appsettings.json: "ConnectionStrings": { "Shop": "Server=.;Database=Shop;Trusted_Connection=True;TrustServerCertificate=True" }ts
// src/app/features/products/data/product.model.ts
export interface Product { id: number; name: string; price: number; }
// src/app/features/products/data/product.service.ts
@Injectable({ providedIn: 'root' })
export class ProductService {
private http = inject(HttpClient);
private base = `${environment.apiUrl}/products`;
list() { return this.http.get<Product[]>(this.base); }
get(id: number) { return this.http.get<Product>(`${this.base}/${id}`); }
create(p: Omit<Product, 'id'>) { return this.http.post<Product>(this.base, p); }
}
// src/app/features/products/product-list/product-list.ts
@Component({
selector: 'app-product-list',
template: `
@if (products.isLoading()) { <p>Loading…</p> }
@else if (products.error()) { <p>Could not load products.</p> }
@else { <ul>@for (p of products.value(); track p.id) { <li>{{ p.name }} — {{ p.price | currency:'INR' }}</li> }</ul> }
`,
imports: [CurrencyPipe],
})
export class ProductList {
private service = inject(ProductService);
products = rxResource({ stream: () => this.service.list() }); // signal-based resource (Angular 19+/20)
}json
// proxy.conf.json — referenced from angular.json "serve" options ("proxyConfig": "proxy.conf.json")
{ "/api": { "target": "https://localhost:7001", "secure": false, "changeOrigin": true } }Production: build with ng build, host the dist/ files on IIS/Static Web Apps/CDN (SPA fallback rewrite to index.html), and either serve the API on the same domain or enable CORS for the Angular origin. The connection string lives only in the API (appsettings / Key Vault), never in Angular environment files — those ship to the browser.