Skip to content

Angular HTTP calls with simple express backend. And using Environmental files in Angular 15+ with environment variables. This is Angular 18 project

License

Notifications You must be signed in to change notification settings

actionanand/angular-http-project

Repository files navigation

Angular HTTP Call with Simple backend

This project was generated with Angular CLI version 18.2.3.

How to run backend (Express App)

  1. Navigate to backend folder by cd backend/
  2. Install dependencies yarn install
  3. Run the express server yarn start
  4. Open the URL http://localhost:3000/places in your browser

Configure proxy file

Change the value of target in proxy file as your backend api url

Run Angular with proxy server

yarn develop

Generating Environmental files in Angular 15+

ng g environments

Cloning Guide

  1. Clone only the remote primary HEAD (default: origin/master)
git clone <url> --single-branch
  1. Only specific branch
git clone <url> --branch <branch> --single-branch [<folder>]
git clone <url> --branch <branch>
  1. Cloning repositories using degit

    • master branch is default.
npx degit github:user/repo#branch-name <folder-name>
  1. Cloning this project with skeleton
git clone https://github.com/actionanand/angular-http-project.git --branch 1-skeleton angular-proj-name
npx degit github:actionanand/angular-http-project#1-skeleton angular-proj-name

Automate using Prettier, Es Lint and Husky

  1. Install the compatible node version
  nvm install v20.13.1
  1. Install and Configure Prettier

    • Install prettier as below:
      yarn add prettier -D
    • Create a .prettierrc file and write down the format as below: - online ref
    trailingComma: 'all'
    tabWidth: 2
    useTabs: false
    semi: true
    singleQuote: true
    bracketSpacing: true
    bracketSameLine: true
    arrowParens: 'avoid'
    printWidth: 120
    overrides:
      - files:
          - '*.js'
          - '*.jsx'
        options:
          bracketSpacing: true
          jsxSingleQuote: true
          semi: true
          singleQuote: true
          tabWidth: 2
          useTabs: false
      - files:
          - '*.ts'
        options:
          tabWidth: 2
    • Create a .prettierignore file and write as below(sample)
    # Ignore artifacts:
    build
    coverage
    e2e
    node_modules
    dist
    dest
    reports
    
    # Ignore files
    *.lock
    package-lock.json
    yarn.lock
  2. Install Es Lint, if not installed

ng add @angular-eslint/schematics

if error comes, use the below command

ng add @angular-eslint/schematics@next
  1. Configure pre-commit hooks

Pre-commit hooks are a nice way to run certain checks to ensure clean code. This can be used to format staged files if for some reason they weren’t automatically formatted during editing. husky can be used to easily configure git hooks to prevent bad commits. We will use this along with pretty-quick to run Prettier on our changed files. Install these packages, along with npm-run-all, which will make it easier for us to run npm scripts:

yarn add husky pretty-quick npm-run-all -D

To configure the pre-commit hook, simply add a precommit npm script. We want to first run Prettier, then run TSLint on the formatted files. To make our scripts cleaner, I am using the npm-run-all package, which gives you two commands, run-s to run scripts in sequence, and run-p to run scripts in parallel:

  "precommit": "run-s format:fix lint",
  "format:fix": "pretty-quick --staged",
  "format:check": "prettier --config ./.prettierrc --list-different \"src/{app,environments,assets}/**/*{.ts,.js,.json,.css,.scss}\"",
  "format:all": "prettier --config ./.prettierrc --write \"src/{app,environments,assets}/**/*{.ts,.js,.json,.css,.scss}\"",
  "lint": "ng lint",
  1. Initialize husky

    • Run it once
      npm pkg set scripts.prepare="husky install"
      npm run prepare
    • Add a hook
      npx husky add .husky/pre-commit "yarn run precommit"
      npx husky add .husky/pre-commit "yarn test"
      git add .husky/pre-commit
    • Make a commit
      git commit -m "Keep calm and commit"
      # `yarn run precommit and yarn test` will run every time you commit
  2. How to skip prettier format only in particular file

    1. JS
    matrix(1, 0, 0, 0, 1, 0, 0, 0, 1);
    
    // prettier-ignore
    matrix(
        1, 0, 0,
        0, 1, 0,
        0, 0, 1
      )
    1. JSX
    <div>
      {/* prettier-ignore */}
      <span     ugly  format=''   />
    </div>
    1. HTML
    <!-- prettier-ignore -->
    <div         class="x"       >hello world</div            >
    
    <!-- prettier-ignore-attribute -->
    <div (mousedown)="       onStart    (    )         " (mouseup)="         onEnd      (    )         "></div>
    
    <!-- prettier-ignore-attribute (mouseup) -->
    <div (mousedown)="onStart()" (mouseup)="         onEnd      (    )         "></div>
    1. CSS
    /* prettier-ignore */
    .my    ugly rule
      {
    
      }
    1. Markdown
      <!-- prettier-ignore -->
    
    Do not format this
    1. YAML
    # prettier-ignore
    key  : value
      hello: world
    1. For more, please check

Resources

Wiki

What are Angular interceptors?

Interceptors are unique Angular services that we can implement to add behavior to HTTP requests in our application. HttpInterceptor provides a way to intercept HTTP requests and responses. In this sense, each interceptor can handle the request entirely by itself.

image

As the diagram above shows, the interceptors are always in the middle of an HTTP request. As middlemen, they allow us to perform operations on the requests on their way to and back from the server, making it a perfect place to centralize code for things like adding headers, passing tokens, caching, and error handling.

  1. Angular Error Interceptor
  2. Transitioning from retryWhen to retry with Delay in RxJS
  3. Retry Error HTTP Requests in Angular (without retryWhen)
  4. Angular 17: HTTP Interceptors guide
  5. mergeMap – RxJS Reference
// The Old Way: `retryWhen`
import { throwError, retryWhen, delay, tap, scan } from 'rxjs';

function usingRetryWhen(duration, maxtries) {
  return retryWhen(errors =>
    errors.pipe(
      scan((count, err) => {
        if (count >= maxtries) {
          throw err;
        }
        return count + 1;
      }, 0),
      tap(val => console.log(`#${val} Attemp with RetryWhen`)),
      delay(duration),
    ),
  );
}

let triggerErrorWithRetryWhen = throwError(() => new Error('Test Error'));

triggerErrorWithRetryWhen.pipe(usingRetryWhen(2000, 2)).subscribe({
  next: val => console.log(val, 'from next'),
  error: val => console.log(val, 'from error'),
});
// The New Way: `retry` with `delay`
import { throwError, retry, timer } from 'rxjs';

function retryWithDelay(duration, maxTries) {
  return retry({
    count: maxTries,
    delay: (error, retryCount) => {
      console.log(`Retry attempt #${retryCount}`);
      return timer(duration);
    },
  });
}

let triggerErrorWithRetry = throwError(() => new Error('Test Error'));

triggerErrorWithRetry.pipe(retryWithDelay(2000, 2)).subscribe({
  next: val => console.log(val, 'from next'),
  error: val => console.log(val, 'from error'),
});