Master Angular From Scratch

Learn Angular with clear, interactive, and structured lessons for beginners and developers.

ANGULAR COURSE SYLLABUS
1. Angular Introduction
Angular Introduction Angular History Angular Fundamentals Angular Architecture Component-Based Angular
2. Angular Setup
Angular Setup Introduction Installing Node.js Installing Angular CLI Creating an Angular Application Angular Project Structure
3. Components
Components Overview Component Anatomy Creating Components Component Selector Component Template Component Styles Component Metadata Standalone Components Parent and Child Components Reusable Components
4. Templates
Templates Introduction Template Syntax Template Expressions Template Statements Template Reference Variables ng-template ng-container ngTemplateOutlet Built-in Control Flow
5. Data Binding
Data Binding Introduction Interpolation Binding Property Binding Event Binding Two-Way Data Binding Class & Style Binding
6. Directives
Directives Introduction Attribute Directives Structural Directives Custom Directives
7. Pipes
Pipes Introduction Built-in Pipes Parameterized Pipes Chaining Pipes Custom Pipes
8. Event Handling
Event Handling Introduction DOM Events Event Binding Syntax Event Object Passing Data to Event Handlers
9. Input & Output
Component Communication @Input @Output EventEmitter
10. Lifecycle Hooks
Lifecycle Hooks Introduction ngOnInit ngOnChanges ngAfterViewInit ngOnDestroy
11. Services
Services Introduction Creating Angular Services Using Services in Components Sharing Data Through Services Service Scope
12. Dependency Injection
Dependency Injection Introduction Injecting Dependencies InjectionToken Provider Configuration
13. Routing
Routing Introduction Route Configuration RouterLink & Navigation Route Parameters Child Routes Route Guards
14. Forms
Angular Forms Introduction Template-Driven Forms Reactive Forms Form Validation Form Submission & Error Handling
15. HttpClient
HttpClient Introduction Configuring HttpClient GET Request POST, PUT & DELETE Requests Headers & Parameters HTTP Error Handling
16. Observables
Observables Introduction Creating & Subscribing to Observables Observable Data Streams Observable Operators Subscription Management
17. RxJS
RxJS Introduction RxJS Operators Transformation & Filtering Combining Observables Higher-Order Mapping Subjects
18. API Integration
API Integration Introduction Connecting Angular with REST API Consuming API Data CRUD API Integration API Response & Error Handling

RxJS Subjects

Learn what RxJS Subjects are, how they work as both Observables and Observers, and how Subject types can be used for sharing and distributing values.

What is a Subject?

A Subject is a special type of RxJS Observable that can also receive values.

Unlike a normal Observable where values are generally produced by the Observable source, a Subject allows application code to call methods such as next() and send values to its subscribers.

A Subject can therefore act as both an Observable and an Observer.

Subject Working Flow

Producer Sends Value
→
Subject Receives Value
→
Subscriber 1 Receives Value
+
Subscriber 2 Receives Value

Subject as Observable and Observer

O
As Observable

Other parts of the application can subscribe to the Subject.

R
As Receiver

The Subject can receive values through next().

M
Multicast

One emitted value can be delivered to multiple subscribers.

S
Shared Stream

Multiple consumers can observe the same Subject stream.

Creating a Subject

TypeScript
import { Subject } from '@rxjs';

const courseSubject =
    new Subject<string>();

Subscribing to a Subject

A Subject can have multiple subscribers.

When the Subject emits a value using next(), each active subscriber receives that value.

Subscribers
courseSubject.subscribe({

    next: course => {

        console.log(
            'Subscriber 1:',
            course
        );

    }

});


courseSubject.subscribe({

    next: course => {

        console.log(
            'Subscriber 2:',
            course
        );

    }

});

Emitting Values with next()

Emit Values
courseSubject.next(
    'Java Full Stack'
);

courseSubject.next(
    '.NET Full Stack'
);

courseSubject.next(
    'Python Full Stack'
);

Subject Output

Subscriber 1: Java Full Stack

Subscriber 2: Java Full Stack

Subscriber 1: .NET Full Stack

Subscriber 2: .NET Full Stack

Both active subscribers receive each emitted value.

Subject and Multicasting

A Subject can multicast a value to multiple subscribers.

When the Subject emits a value, all subscribers that are currently connected to the Subject receive that emission.

next() One Value
→
Subject Multicast
→
Subscriber A Same Value
+
Subscriber B Same Value

Late Subscribers

A normal Subject does not automatically replay values that were emitted before a subscriber joined.

This is an important difference between a regular Subject and subjects such as BehaviorSubject and ReplaySubject.

Example
const subject =
    new Subject<string>();


subject.next(
    'Java Full Stack'
);


subject.subscribe({

    next: value => {

        console.log(value);

    }

});


subject.next(
    '.NET Full Stack'
);

Output

.NET Full Stack

BehaviorSubject

A BehaviorSubject requires an initial value and stores the latest emitted value.

A new subscriber immediately receives the current value when it subscribes.

Example
import {
    BehaviorSubject
} from '@rxjs';

const courseSubject =
    new BehaviorSubject<string>(
        'Angular'
    );


courseSubject.subscribe({

    next: course => {

        console.log(course);

    }

});

Initial Value

Angular

Updating BehaviorSubject

Example
const courseSubject =
    new BehaviorSubject<string>(
        'Angular'
    );


courseSubject.next(
    'React'
);


courseSubject.next(
    'Node.js'
);

The latest emitted value remains available as the current value for future subscribers.

ReplaySubject

A ReplaySubject can replay previously emitted values to a new subscriber according to the configured buffer.

It is useful when a subscriber needs access to recent values that were emitted before the subscription started.

Example
import {
    ReplaySubject
} from '@rxjs';

const courseSubject =
    new ReplaySubject<string>(2);


courseSubject.next(
    'Java'
);

courseSubject.next(
    '.NET'
);

courseSubject.next(
    'Python'
);


courseSubject.subscribe({

    next: course => {

        console.log(course);

    }

});

Replayed Values

.NET

Python

AsyncSubject

An AsyncSubject emits the latest value to subscribers only when the Subject completes.

If the Subject completes without emitting a value, no value is delivered to subscribers.

Example
import {
    AsyncSubject
} from '@rxjs';

const resultSubject =
    new AsyncSubject<number>();


resultSubject.subscribe({

    next: value => {

        console.log(value);

    }

});


resultSubject.next(10);
resultSubject.next(20);
resultSubject.next(30);

resultSubject.complete();

Output

30

Types of RxJS Subjects

S
Subject

Multicasts values to current subscribers.

B
BehaviorSubject

Stores and emits the current value to new subscribers.

R
ReplaySubject

Replays previously emitted values according to its buffer.

A
AsyncSubject

Emits the latest value when the Subject completes.

Subject Types Comparison

Subject Type Initial Value New Subscriber Receives Main Feature
Subject Not required Future emissions Multicast current values
BehaviorSubject Required Current/latest value Stores current value
ReplaySubject Not required Buffered previous values Replays values
AsyncSubject Not required Latest value after completion Final-value emission

Subject vs Observable

Feature Observable Subject
Can Subscribe Yes Yes
Can Call next() Not from the consumer API Yes
Multiple Subscribers Depends on the source and sharing strategy Yes, values are multicasted
Manual Emission Source controls emissions next() can emit values
Special Variants No Subject-specific variants BehaviorSubject, ReplaySubject, AsyncSubject

CIIT Training Institute Example

Suppose the CIIT Training Institute application has a selected-course stream that is used by multiple components.

A BehaviorSubject can store the current selected course so that subscribers can receive the latest value.

Course Selection Service
import {
    BehaviorSubject
} from '@rxjs';

export class CourseStateService {

    private selectedCourseSubject =
        new BehaviorSubject<string>(
            'Java Full Stack'
        );

    selectedCourse$ =
        this.selectedCourseSubject
            .asObservable();


    selectCourse(course: string) {

        this.selectedCourseSubject
            .next(course);

    }

}
Component
this.courseStateService
    .selectedCourse$
    .subscribe({

        next: course => {

            console.log(
                'Selected Course:',
                course
            );

        }

    });

CIIT Training Institute

Selected Course: Java Full Stack

Other components can subscribe to the shared course state.

Using asObservable()

A Subject can expose an Observable view using asObservable().

This is useful when other parts of the application should subscribe to a stream without directly calling next() on the underlying Subject.

Example
private courseSubject =
    new BehaviorSubject<string>(
        'Java Full Stack'
    );


course$ =
    this.courseSubject
        .asObservable();

Subject Lifecycle

Create Subject
→
Subscribe Consumers Connect
→
next() Emit Values
→
complete() End Stream

complete() and error()

Subject Lifecycle Example
const subject =
    new Subject<string>();


subject.subscribe({

    next: value => {

        console.log(value);

    },

    error: error => {

        console.error(error);

    },

    complete: () => {

        console.log(
            'Completed'
        );

    }

});


subject.next('Angular');

subject.complete();

After a Subject has completed or errored, it cannot continue its normal emission lifecycle.

When Can Subjects Be Useful?

S
Shared State

Share a value or state stream between multiple consumers.

E
Events

Represent application events that multiple consumers need.

N
Notifications

Broadcast application notifications to subscribers.

C
Communication

Coordinate communication between services and consumers.

Avoid Unnecessary Subjects

Subjects are useful, but every Observable-based problem does not require a Subject.

When data can be represented cleanly using a normal Observable pipeline, introducing a Subject may add unnecessary state or lifecycle complexity.

RxJS Subject Best Practices

  • Use Subject when the application genuinely needs manual emission or multicasting behavior.
  • Use BehaviorSubject when a current value needs to be retained and made available to new subscribers.
  • Use ReplaySubject when recent past values need to be replayed.
  • Keep Subjects private inside services when external consumers only need to observe the stream.
  • Expose a read-only Observable using asObservable() where appropriate.
  • Avoid using Subjects everywhere when a normal Observable pipeline provides a simpler solution.

Important Points

1. Subject Can Receive Values

A Subject exposes methods such as next() that can be used to emit values.

2. Subject Can Have Multiple Subscribers

Active subscribers receive the values emitted by the Subject.

3. Subject Types Have Different Behavior

BehaviorSubject, ReplaySubject and AsyncSubject are designed for different value-delivery requirements.

4. Protect Internal Subjects

Keeping a Subject private and exposing an Observable view can provide better control over who can emit values.

Summary

A Subject is an RxJS type that can act as both an Observable and an Observer.

BehaviorSubject stores the current value, ReplaySubject can replay buffered values, and AsyncSubject emits its latest value when it completes.

Subjects are useful for multicasting and shared reactive state, but they should be introduced only when their behavior is actually required. The RxJS module is now complete .