Chapter 6: SportsStore: Orders and Checkout
Связь между /store и /cart через src/app/model/cart.model.ts
Path | Component | Function |
---|---|---|
/store |
|
Add to Cart button |
/cart |
|
Товары в корзине |
/checkout |
|
Форма с адресом доставки |
/admin/main/products |
|
Таблица товаров |
/admin/main/products/edit/1 |
|
Редактирование товара |
Angular Basics
-
Angular CLI Commands:
-
Create a new Angular app:
ng new my-app
-
Generate components, services, modules, etc.:
ng generate component my-component
-
-
Angular Components:
-
Building blocks of Angular applications.
-
Create a component:
ng generate component my-component
-
Components consist of a TypeScript class, an HTML template, and a CSS style file.
-
-
Templates:
-
HTML files defining the component’s UI.
-
Use double curly braces
{{ }}
for data binding.
-
-
Directives:
-
*ngIf
: Conditional rendering. -
*ngFor
: Looping through arrays.
-
-
Interpolation:
-
{{ variableName }}: Display dynamic data in templates.
-
-
Event Binding:
-
(event)="function()"
: React to user events (e.g., clicks).
-
-
Property Binding:
-
[property]="value"
: Bind a property to a component property.
-
-
Two-way Data Binding:
-
[(ngModel)]="property"
: Bind input field and component property (requires FormsModule).
-
Angular Modules
-
NgModule:
-
Decorator for creating Angular modules.
-
Every app has at least one module (the root module).
-
-
Declarations:
-
List of components, directives, and pipes used within the module.
-
-
Imports:
-
Other modules that this module depends on.
-
-
Providers:
-
Services and dependencies.
-
Angular Services
-
Services:
-
Singleton objects used to share data and logic.
-
Generate a service:
ng generate service my-service
-
-
Dependency Injection:
-
Inject services into components and other services.
-
Routing
-
RouterModule:
-
Provides routing and navigation functionality.
-
-
Routes:
-
Define application routes with associated components.
-
-
Router Outlet:
-
Placeholder where routed component views are displayed.
-
Forms
-
FormsModule and ReactiveFormsModule:
-
For handling forms in Angular.
-
-
Template-driven Forms:
-
Use Angular directives in the template.
-
-
Reactive Forms:
-
Create forms programmatically with FormControl and FormGroup.
-
Observables
-
RxJS:
-
Angular extensively uses RxJS for handling asynchronous operations.
-
-
Observable:
-
Represents a stream of data over time.
-
-
Subscriptions:
-
Subscribe to observables to receive data.
-
HTTP
-
HttpClient:
-
Angular’s module for making HTTP requests.
-
-
GET, POST, PUT, DELETE:
-
HTTP methods for interacting with a server.
-
Lifecycle Hooks
-
ngOnInit, ngOnDestroy, etc.:
-
Methods to react to component lifecycle events.
-
-
ngOnChanges:
-
React to input property changes.
-
-
ngDoCheck:
-
Detect and act upon changes in a component.
-
Testing
-
Karma:
-
Test runner for Angular applications.
-
-
Jasmine:
-
Testing framework for writing unit tests.
-
TypeScript Basics
-
Installing TypeScript:
-
Install TypeScript globally:
npm install -g typescript
-
-
Creating a TypeScript File:
-
Create a
.ts
file, e.g.,app.ts
.
-
-
Compiling TypeScript:
-
Compile TypeScript to JavaScript:
tsc app.ts
-
-
Running TypeScript:
-
Use Node.js or a browser to run the generated JavaScript.
-
Variables and Types
-
Variable Declarations:
-
Declare variables with
let
,const
, orvar
.
-
-
Type Annotations:
-
Use
:
to specify variable types, e.g.,let name: string
.
-
-
Basic Types:
-
string
,number
,boolean
,null
,undefined
,symbol
,object
,any
.
-
-
Arrays and Tuples:
-
let list: number[] = [1, 2, 3];
-
Tuple:
let tuple: [string, number] = ['hello', 42];
-
-
Enums:
-
Create enum types:
enum Color { Red, Green, Blue };
-
Functions
-
Function Declarations:
-
Define functions with type annotations:
-
function greet(name: string): string {
return `Hello, ${name}!`;
}
-
Optional and Default Parameters:
-
Make parameters optional with
?
and provide defaults.
-
-
Rest Parameters:
-
Collect multiple parameters into an array using
…
.
-
Interfaces
-
Defining Interfaces:
-
Declare object shapes with interfaces:
-
interface Person {
name: string;
age?: number;
}
-
Implementing Interfaces:
-
Implement interfaces in classes.
-
-
Extending Interfaces:
-
Extend interfaces to create new ones.
-
Classes
-
Class Declarations:
-
Define classes with properties and methods:
-
class Car {
make: string;
constructor(make: string) {
this.make = make;
}
}
-
Inheritance:
-
Use
extends
to create subclasses.
-
-
Access Modifiers:
-
Control access to class members with
public
,private
, andprotected
.
-
Modules
-
Exporting and Importing:
-
Export modules with
export
and import them withimport
.
-
-
Default Exports:
-
Use
export default
for the default export of a module.
-
Generics
-
Generic Functions:
-
Create reusable functions and classes with generics.
-
function identity<T>(arg: T): T {
return arg;
}
-
Generic Constraints:
-
Restrict the types that can be used with generics.
-
function getLength<T extends { length: number }>(arg: T): number {
return arg.length;
}
Type Assertion
-
Type Assertion:
-
Use
<Type>
orvalue as Type
to assert a type when necessary.
-
let value: any = 'Hello, TypeScript!';
let length = (value as string).length;
Declaration Files
-
Declaration Files (.d.ts):
-
Use declaration files to define types for third-party libraries.
-
TypeScript Configuration
-
tsconfig.json:
-
Configure TypeScript settings in a
tsconfig.json
file.
-
-
Compiler Options:
-
Set compiler options like target, module, and outDir.
-
RxJS Basics
-
Installing RxJS:
-
Install RxJS using npm:
npm install rxjs
-
-
Importing RxJS:
-
Import RxJS features using
import { Observable, of, from, Subject } from 'rxjs';
-
-
Creating Observables:
-
Create observables with
Observable.create()
,of()
, orfrom()
.
-
-
Subscribing to Observables:
-
Subscribe to an observable using the
subscribe()
method.
-
-
Unsubscribing:
-
Unsubscribe from an observable to prevent memory leaks:
subscription.unsubscribe();
-
Operators
-
Pipeable Operators:
-
Use operators like
map()
,filter()
,mergeMap()
, andswitchMap()
to transform and manipulate data streams.
-
-
Chaining Operators:
-
Chain multiple operators together using the
pipe()
method.
-
-
Creating Operators:
-
Create custom operators by defining functions that return functions.
-
Subjects
-
Subjects:
-
Subjects are both observables and observers.
-
Use
Subject
,BehaviorSubject
, orReplaySubject
.
-
-
Publishing Values:
-
Publish values to multiple subscribers using a subject.
-
-
Complete and Error:
-
Subjects can complete or emit errors using
complete()
anderror()
methods.
-
Operators for Combining Observables
-
merge():
-
Merge multiple observables into one.
-
-
concat():
-
Concatenate observables sequentially.
-
-
forkJoin():
-
Wait for all observables to complete and emit their last values.
-
-
zip():
-
Combine values from multiple observables sequentially.
-
Error Handling
-
catchError():
-
Handle errors gracefully within an observable pipeline.
-
-
retry():
-
Retry an observable sequence on error.
-
Hot vs. Cold Observables
-
Cold Observables:
-
Produce data only when subscribed.
-
Each subscriber gets its own independent sequence.
-
-
Hot Observables:
-
Produce data continuously, even when there are no subscribers.
-
Subscribers share the same sequence.
-
Schedulers
-
Schedulers:
-
Control the execution context and timing of observables.
-
Use schedulers like
asyncScheduler
,queueScheduler
, andanimationFrameScheduler
.
-
-
observeOn():
-
Specify the scheduler on which to observe values.
-
Subjects vs. Observables
-
Subjects:
-
Both observable and observer.
-
Use when you need to multicast values to multiple subscribers.
-
-
Observables:
-
Only observable.
-
Use for one-to-one data streaming.
-
Real-World Use Cases
-
HTTP Requests:
-
Use RxJS for handling HTTP requests using Angular’s HttpClient.
-
-
User Input Handling:
-
Manage user interactions and debouncing.
-
-
WebSocket Communication:
-
Handle real-time data streams with WebSockets.
-
-
State Management:
-
Implement state management solutions like NgRx with RxJS in Angular.
-