angular 8 best practices code example

Example 1: angular 7 folder structure best practices

|-- app     |-- modules       |-- home           |-- [+] components           |-- [+] pages           |-- home-routing.module.ts           |-- home.module.ts     |-- core       |-- [+] authentication       |-- [+] footer       |-- [+] guards       |-- [+] http       |-- [+] interceptors       |-- [+] mocks       |-- [+] services       |-- [+] header       |-- core.module.ts       |-- ensureModuleLoadedOnceGuard.ts       |-- logger.service.ts     |     |-- shared          |-- [+] components          |-- [+] directives          |-- [+] pipes          |-- [+] models     |     |-- [+] configs|-- assets     |-- scss          |-- [+] partials          |-- _base.scss          |-- styles.scss

Example 2: angular best practices unsubscribe

/* Best practice is to create a base class and move gererik handling to it */

import { Subscription, Observable } from 'rxjs';
import { OnDestroy } from '@angular/core';


export abstract class ComponentBase implements OnDestroy {

  set subs(subscription: Subscription) {
    this.subscriptioions.add(subscription);
  }

  private subscriptioions = new Subscription();

  constructor() {};

  subscribe(service: Observable<any>, successFn: (value: any) => void, errorHandler?: (value: any) => void) {
    this.subs = service.subscribe(successFn, errorHandler || this.errorHandler);
  }

  ngOnDestroy() {
    this.subscriptioions.unsubscribe();
  }

  private errorHandler(error) {
    // TODO: generic error handling
  }
}

/* implementation in a component */
// No need to explicitly subscribe or unsubscribe on destroy

const product$ = this.productService.getProducts(productId);
this.subscribe(product$, (product) => {
	// TODO: use product
});