Angular Architecture/Best Practices Flashcards
software requirements
Node js, Angular CLI, VS code
Architecture Considerations
APP OVERVIEW - what is the application for, what are the goals, how is the client going to use it, what are the business and strategic benefits
APP FEATURES
DOMAIN SECURITY - are we using roles on the server side, groups, claims; how are they going to be communicated to angular app; how is angular going to communicate with our api, is it going to use token based or ldap with active directory
DOMAIN RULES - are they going to run on client side or server side. we need to run on both sides is good for validations. there were might be some number crunching ones, which might need api call and run on the server
LOGGING: when error in front end application
api or integrate with cloud
it helps in bug support and also have good statistics about the app
SERVICE/COMMUNICATION: how angular app is going to talk to the server
normally it is http/https
if your app might have real time data considerations then web sockets might be
not just thinking about data exchange between front end and back end but thinking about between service and components is helpful
DATA MODEL: api to angular; what are we passing to components
are we getting what we want from the api. in many cases data models with api give lot of data, we might only need subset of the data;
we might need to think if we are going to use viewmodel, models only the component needs
FEATURE COMPONENTS: what are our feature components and how are we going to structure our feature components
component commucation -
we might need to know key features upfront
SHARED FUNCTIONALITY- any 3 rd party components that we are going to use
are we going to use them directly or use a wrapper
shared in just one app or use across app; then we think about libraries
Architecture planning Template
https://docs.google.com/presentation/d
/1jrkbbB3eRtTOrbkaljQxLuypHsdUHDl3_
4uFFnHTSNo/edit#slide=id.p4
https: //codewithdan.me/angular-architecture-planning
https: //codewithdan.me/angular-architecture-planning-example
Domain Security
using tokens
using HttpInterceptor could be used to set auth header
what is the back end that issues token, and refresh tokens
Domain Rules
validation
Route guard for not to access without login
validate credentials
Logging
Azure app insights angular service for logging Handle errors based on different environment dev/stage/prod i used ngx-logger nlog - graylog
Services/communication
restful services -on back for this project node.js is being used. it could be java asp.net core, php Angular services below: Data service : use http client ; for customer/orders and login/logout(auth) Sorting Service Filtering Service Logger Service Mediator/bus if needed Component to component communication
HttpInterceptor will set token for HTTP requests if token GET/PUT/POST/DELETE/PATCH - to set header
Use PATCH - to update specific properties - one or two properties
Data Models
Application Models/Interface
Create class or just use interface on the client side
if we use interface, there is zero impact on the bundle size for production
it is better to opt for interfaces unless the classes are more specialized; like if model has properties and models
if you are just using the data from the server or using the object to scale to a smaller object then interfaces are just fine on client side
Interface is great for intellisense or code help
How to reduce the bundle size
How to reduce the bundle size
Feature Components
decide what are angular components needed for features of the app
Shared Functionality
Toast Modal Dialog Google map pager Menu Grid/cards
are these just feature used once or used in multiple feature components
this decides where to pull these in the folder hierrachy
if they are going to used by other applications then we could have a shared library
any 3 rd party components like prime Ng Ng Bootstrap Angular Material ag-grid
Take time for architecture it helps
you will be so much ahead in planning the application architecture
The folder layout
the reuse of code
we might change, as we are still in the initial phase
angular style guide
https://angular.io/guide/styleguide coding conventions naming rules application sturcture organizing modules creating and using components creating and using services life cycle hooks
Other considerations
Accessibilty - may be design consideration
i18n - Internationalization
Environments-
CI/CD
CDN/Container/Server - how are we deploying code to production
course on containerizing angular applications with docker
Unit testing- built in cli tools, karma test runner
End to end testing - protractor or Cypress
this might impact your design; the testers might prefer to have id on all the tags to make it easy to find
API’s - backend where the security happens; data validation
Performance of the application
Documentation
Organizing Features
Do structure the app such that you can LOCATE code quickly, IDENTIFY the code at glance, keep the FLATTEST structure you can, and TRY to be DRY (Do not repeat yourself)
LIFT
LOCATE CODE QUICKLY-
easy to structure the folder structure; once we get bundles it does not matter
IDENTIFY THE CODE AT A GLANCE- how we name our files like feature.component.ts data.service.ts canactivate.guard.ts = for route guards
KEEP THE FLATTEST STRUCTURE YOU CAN-
do not keep nested folders
Try to be DRY:
like we could use services to reuse
we could reuse directives and components
Organizing files - convention based - may be not recommended if there are multiple features
like putting all the components in one folder
putting all the services in one folder
like MVC pattern
Follow strict naming conventions
Related code may be separated
can result in a lot of files in a folder in larger applications
views would be different places
Organizing files - Feature based - Recommended and CLI does by default
May be you could have Feature folder like Customers
and have many components like edit,grid,cards
that are part of the feature
if there are too many then you could have subfolder called components like feature- Customer - Components - put all the components related
it has one extra layer in the es2015 import statement
Features are organized into their own folders
Features are self-contained
Easy to find everything related to a feature
Organizing files - Feature based -how to implement
use angular cli to generate initial feature folder/component ; you could even flatten without creating sub folders
Minimum of one Module per feature (as appropriate) - it helps in lazy loading ; it helps in features to be self-contained; it could be imported at the root module or some other feature if needed ;it is good for maintainence
Avoid Deeply nested folders
Flatten Feature hierrachies - application might have hierrachies like Course-exercise-lab but your code should have exercise folder, course folder, items folder instead of having them in hierarchy
Flatten out top level features as much as possible; this will reduce the need to add ../,../ in the code
if you have nested features that is okey, but be cautious about how deeply you want to nest
Flattening makes - imports to be easier, refactor to be easier, easy to find components
Feature Modules
let us assume we have customer feature and orders feature
ng g c customer = it creates customer component with a folder created at the top level
people normally add this feature in the root module; there is nothing wrong in it as the app grows and grows and gets more feature;
we have one module, we can not use lazy loading and the features are no longer self-contained
usually we could have one module per feature but often instructor has 2
Feature has routing; so we have feature routing module defined with in a module in the feature itself customers-routing.module.ts that would be imported into module for this feature customer.module.ts
if you have complex subfeatures, you would want them to be self-contained, if the portion of the team does it. root module does not need to worry about it
so we are going to have feature-routing module and feature module
Angular Style Guide-Single responsibility
Apply the single responsibility principle (SRP) to all components, services, and other symbols. This helps make the app cleaner, easier to read and maintain, and more testable.
Do define one thing, such as a service or component, per file.
Consider limiting files to 400 lines of code.
Why? One component per file makes it far easier to read, maintain, and avoid collisions with teams in source control.
Why? One component per file avoids hidden bugs that often arise when combining components in a file where they may share variables, create unwanted closures, or unwanted coupling with dependencies.
Why? A single component can be the default export for its file which facilitates lazy loading with the router.
The key is to make the code more reusable, easier to read, and less mistake prone.
ASG - Small functions
Do define small functions
Consider limiting to no more than 75 lines.
Why? Small functions are easier to test, especially when they do one thing and serve one purpose.
Why? Small functions promote reuse.
Why? Small functions are easier to read.
Why? Small functions are easier to maintain.
Why? Small functions help avoid hidden bugs that come with large functions that share variables with external scope, create unwanted closures, or unwanted coupling with dependencies.
ASG -Naming
Do follow a pattern that describes the symbol’s feature then its type. The recommended pattern is feature.type.ts.
Naming conventions are hugely important to maintainability and readability. This guide recommends naming conventions for the file name and the symbol name.
General Naming Guidelines
Style 02-01
Do use consistent names for all symbols.
Do follow a pattern that describes the symbol’s feature then its type. The recommended pattern is feature.type.ts.
Why? Naming conventions help provide a consistent way to find content at a glance. Consistency within the project is vital. Consistency with a team is important. Consistency across a company provides tremendous efficiency.
Why? The naming conventions should simply help find desired code faster and make it easier to understand.
Why? Names of folders and files should clearly convey their intent. For example, app/heroes/hero-list.component.ts may contain a component that manages a list of heroes.
ASG-Separate file names with dots and dashes
Do use dashes to separate words in the descriptive name.
Do use dots to separate the descriptive name from the type.
Do use consistent type names for all components following a pattern that describes the component’s feature then its type. A recommended pattern is feature.type.ts.
Do use conventional type names including .service, .component, .pipe, .module, and .directive. Invent additional type names if you must but take care not to create too many.
Why? Type names provide a consistent way to quickly identify what is in the file.
Why? Type names make it easy to find a specific file type using an editor or IDE’s fuzzy search techniques.
Why? Unabbreviated type names such as .service are descriptive and unambiguous. Abbreviations such as .srv, .svc, and .serv can be confusing.
Why? Type names provide pattern matching for any automated tasks.
customer works!
> Customer Detail component: export class CustomerDetailComponent implements OnInit { @Input() CustomerDetail: any; in html:customer : {{ CustomerDetail.name }}
in appcomponent.html:customer works!
customer : {{ CustomerDetail.name }}{{ value }}
{{ label }}Status: {{ status }}
```Subject
- {{ data.length }}
BehaviorSubject
- {{ data.length }}
ReplaySubject
- {{ data.length }}
AsyncSubject
- {{ data.length }}
Using RxJS Subjects
All of the functionality for this demo is in core/subject.service.ts and the subjects folder. Click Start to begin.Start
Status: {{ status }}
```Subject
- {{ data.length }}
BehaviorSubject
- {{ data.length }}
ReplaySubject
- {{ data.length }}
AsyncSubject
- {{ data.length }}
Subject Only subscribers receive data
BehaviorSubject Note how this picks up the last value emitted event though it subscribed after the value was sent out. That's because BehaviorSubject allows an initial value to be sent to an observer as they subscribe.
ReplaySubject Note how this stays in sync with everything above even though it subscribes 10 seconds after the subject. That's because it's replaying everything up to that point from a cache it maintains.
AsyncSubject This only plays the last item before it completes - nothing before that. It "completes" in the data service once the customers array length is greater than 5.
People and Homeworlds
- {{ char.name }} ({{ char.homeworld.name }})
People and Homeworlds
- {{ char.name }} ({{ char.homeworld.name }})