Strongly Typing the Code

Let's implement strong typing in the services and modules of our application.

Since we’ve already defined the appropriate interfaces, let’s strongly type our code using them.

Strongly typing the services

In our application, we have two services—DataService and ProductsService. In this lesson, we’ll strongly type these services one by one.

Strongly typing the DataService class

Since the products variable in line 13 and the shoppingCart variable in line 81 contain an array of products, let’s specify their type to be Product[] instead of any.

import { Injectable } from '@angular/core';
import { InMemoryDbService } from 'angular-in-memory-web-api';
import { Product } from './app.interfaces';
@Injectable({
providedIn: 'root',
})
export class DataService implements InMemoryDbService {
constructor() {}
createDb() {
// Replacing "any" with "Product[]"
let products: Product[] = [
{
id: 1,
title: 'The Angular Masterclass',
author: 'Educative',
description: 'Learn all about Angular',
imgUrl: '../assets/img/the-angular-masterclass.jpg',
quantity: 124,
price: 24.38,
cart: 0,
},
{
id: 2,
title: 'The Ultimate Guide to Redux',
author: 'Educative',
description: 'Learn about Redux',
imgUrl: '../assets/img/the-ultimate-guide-to-redux.jpg',
quantity: 524,
price: 22.38,
cart: 0,
},
{
id: 3,
title: 'Developing Mobile Apps with Ionic and Angular',
author: 'Educative',
description: 'Learn how to build mobile apps with Ionic and Angular',
imgUrl:
'../assets/img/developing-mobile-apps-with-ionic-and-angular.jpg',
quantity: 146,
price: 38.99,
cart: 0,
},
{
id: 4,
title: 'Angular: Designing and Architecting Web Applications',
author: 'Educative',
description: 'Design and architect your web applications using Angular',
imgUrl:
'../assets/img/angular-designing-and-architecting-web-applications.jpg',
quantity: 500,
price: 11.98,
cart: 0,
},
{
id: 5,
title: 'Developing Robust Angular Applications with AuthO and MongoDB',
author: 'Educative',
description:
'Implement authentication using Angular, AuthO and MongoDB',
imgUrl:
'../assets/img/developing-robust-angular-applications-with-auth0-and-mongodb.jpg',
quantity: 453,
price: 30.18,
cart: 0,
},
{
id: 6,
title: 'Full Reactive Stack with Spring Boot 2 and Spring WebFlux',
author: 'Educative',
description: 'Learn about Spring Boot 2 and Spring WebFlux',
imgUrl:
'../assets/img/full-reactive-stack-with-spring-boot-2-and-spring-webflux.jpg',
quantity: 124,
price: 37.18,
cart: 0,
},
];
let shoppingCart: Product[] = [];
return { products, shoppingCart };
}
}
Strongly typing the DataService class

Strongly typing the ProductsService class

Let’s strongly type the ProductsService class by utilizing the Product interface. The highlighted lines are those in which we replace the keyword any with the Product interface.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, Observable, throwError } from 'rxjs';
import { Product } from './app.interfaces';
@Injectable({
providedIn: 'root',
})
export class ProductsService {
private BASE_URL: string = `api`;
private PRODUCT_URL: string = 'api/products';
private SHOPPING_CART_URL: string = 'api/shoppingCart';
constructor(private httpClient: HttpClient) {}
public getProducts(): Observable<Product[]> {
return this.httpClient
.get<Product[]>(this.PRODUCT_URL)
.pipe(catchError(this.errorHandler));
}
public getProduct(productId: number): Observable<Product> {
return this.httpClient
.get<Product>(`${this.PRODUCT_URL}/${productId}`)
.pipe(catchError(this.errorHandler));
}
public getShoppingCart(): Observable<Product[]> {
return this.httpClient
.get<Product[]>(this.SHOPPING_CART_URL)
.pipe(catchError(this.errorHandler));
}
public addToShoppingCart(product: Product) {
const headers = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
};
return this.httpClient
.post<Product>(`${this.BASE_URL}/shoppingCart`, product, headers)
.pipe(catchError(this.errorHandler));
}
private errorHandler(err: any) {
let errMsg: string;
if (err.error instanceof ErrorEvent) {
errMsg = `Frontend Error: ${err.error.message}`;
} else {
errMsg = `Backend Error Code: ${err.status}: ${err.body.error}`;
}
return throwError(errMsg);
}
}
Strongly typing the ProductsService class

Strongly typing the ProductsModule

Let’s strongly type the NgRx actions, reducers, and selectors of the ProductsModule.

Action

...

Get hands-on with 1400+ tech skills courses.