ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Subjects in Angular

In this tutorial. let us learn RxJs Subject in Angular. The Subjects are special observable which acts as both observer & observable. They allow us to emit new values to the observable stream using the next method. All the subscribers, who subscribe to the subject will receive the same instance of the subject & hence the same values. We will also show the difference between observable & subject. If you are new to observable then refer to our tutorial on what is observable in angular.

What are Subjects ?

A Subject is a special type of Observable that allows values to be multicasted to many Observers. The subjects are also observers because they can subscribe to another observable and get value from it, which it will multicast to all of its subscribers.

Basically, a subject can act as both observable & an observer.

How does Subjects work

Subjects implement both subscribe method and next , error & complete methods. It also maintains a collection of observers[]

image

An Observer can subscribe to the Subject and receive value from it. Subject adds them to its collection observers. Whenever there is a value in the stream it notifies all of its Observers.

The Subject also implements the next, error & complete methods. Hence it can subscribe to another observable and receive values from it.

Creating a Subject in Angular

The following code shows how to create a subject in Angular.

app.component.ts
                              

import { Component, VERSION } from "@angular/core";
import { Subject } from "rxjs";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
 
  subject$ = new Subject();
 
  ngOnInit() {
    
    this.subject$.subscribe(val => {
      console.log(val);
    });
 
    this.subject$.next("1");
    this.subject$.next("2");
    this.subject$.complete();
  }
}
 
                            
                        

The code that creates a subject.

                              

subject$ = new Subject();
                            
                        

We subscribe to it just like any other observable.

                              
 
this.subject$.subscribe(val => {
  console.log(val);
});
 
                            
                        

The subjects can emit values. You can use the next method to emit the value to its subscribers. Call the complete & error method to raise complete & error notifications.

                              
 
this.subject$.next("1");
this.subject$.next("2");
this.subject$.complete();
//this.subject$.error("error")
 
                            
                        

That’s it.

Subject is an Observable

The subject is observable. It must have the ability to emit a stream of values

The previous example shows, we can use the next method to emit values into the stream.

                              
 
this.subject$.next("1");
this.subject$.next("2");
 
                            
                        

Subject is hot Observable

Observables are classified into two groups. Cold & Hot

Cold observable

The cold observable does not activate the producer until there is a subscriber. This is usually the case when the observable itself produces the data.

                              
 
import { Component, VERSION } from "@angular/core";
import { Subject, of } from "rxjs";
 
import { Component, VERSION } from "@angular/core";
import { Observable, of } from "rxjs";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  obs1$ = of(1, 2, 3, 4);
 
  obs$ = new Observable(observer => {
    console.log("Observable starts");
    observer.next("1");
    observer.next("2");
    observer.next("3");
    observer.next("4");
    observer.next("5");
  });
 
  ngOnInit() {
    this.obs$.subscribe(val => {
      console.log(val);
    });
  }
}
 
 
                            
                        

The Producer is one that produces the data. In the above example above it is part of the observable itself. We cannot use that to emit data ourselves.

Even in the following code, the producer is part of the observable.

                              

obs1$ = of(1, 2, 3, 4);
                            
                        

The producer produces the value only when a subscriber subscribes to it.

Hot observable

The hot observable does not wait for a subscriber to emit the data. It can start emitting the values right away. The happens when the producer is outside the observable.

Consider the following example. We have created an observable using subject. In the ngOnInit, we emit the values & close the Subject. That is without any subscribers.

Since there were no subscribers, no one receives the data. But that did not stop our subject from emitting data.

                              

import { Component, VERSION } from "@angular/core";
import { Subject } from "rxjs";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
 
  subject$ = new Subject();
 
  ngOnInit() {
    this.subject$.next("1");
    this.subject$.next("2");
    this.subject$.complete();
  }
}
 
                            
                        

Now, consider the following example. Here the subjects the values 1 & 2 are lost because the subscription happens after they emit values.

                              
 
import { Component, VERSION } from "@angular/core";
import { Subject } from "rxjs";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  subject$ = new Subject();
 
  ngOnInit() {
    this.subject$.next("1");
    this.subject$.next("2");
 
    this.subject$.subscribe(val => {
      console.log(val);
    });
 
    this.subject$.next("3");
    this.subject$.complete();
  }
}
 
                            
                        

Stackblitz

Every Subject is an Observer

The observer needs to implement the next, error & Complete callbacks (all optional) to become an Observer

                              
 
import { Component, VERSION } from "@angular/core";
import { Observable, Subject } from "rxjs";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  subject$ = new Subject();
 
  observable = new Observable(observer => {
    observer.next("first");
    observer.next("second");
    observer.error("error");
  });
 
  ngOnInit() {
    this.subject$.subscribe(val => {
      console.log(val);
    });
 
    this.observable.subscribe(this.subject$);
  }
}
 
                            
                        

The following example creates a Subject & and an Observable

We subscribe to the Subject in the ngOnInit method.

We also subscribe to the observable, passing the subject. Since the subject implements the next method, it receives the values from the observable and emits them to the subscribers.

The Subject here acts as a proxy between the observable & subscriber.

                              

this.observable.subscribe(this.subject$);
                            
                        

Subjects are Multicast

Another important distinction between observable & subject is that subjects are multicast.

More than one subscriber can subscribe to a subject. They will share the same instance of the observable. This means that all of them receive the same event when the subject emits it.

Multiple observers of an observable, on the other hand, will receive a separate instance of the observable.

Multicast vs Unicast

The Subjects are multicast.

Consider the following example, where we have an observable and subject defined. The observable generates a random number and emits it.

                              
 
import { Component, VERSION } from "@angular/core";
import { from, Observable, of, Subject } from "rxjs";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  observable$ = new Observable<number>(subscriber => {
    subscriber.next(Math.floor(Math.random() * 200) + 1);
  });
 
  subject$ = new Subject();
 
  ngOnInit() {
    this.observable$.subscribe(val => {
      console.log("Obs1 :" + val);
    });
 
    this.observable$.subscribe(val => {
      console.log("Obs2 :" + val);
    });
 
    this.subject$.subscribe(val => {
      console.log("Sub1 " + val);
    });
    this.subject$.subscribe(val => {
      console.log("Sub2 " + val);
    });
 
    this.subject$.next(Math.floor(Math.random() * 200) + 1);
  }
}
 
                            
                        

We have two subscribers of the observable. Both these subscribers will get different values. This is because observable on subscription creates a separate instance of the producer. Hence each one will get a different random number

                              

    this.observable$.subscribe(val => {
      console.log("Obs1 :" + val);
    });
 
    this.observable$.subscribe(val => {
      console.log("Obs2 :" + val);
    });
                            
                        

Next, we create two subscribers to the subject. The subject emits the value using the random number. Here both subscribets gets the same value.

                              

    this.subject$.subscribe(val => {
      console.log("Sub1 " + val);
    });
    this.subject$.subscribe(val => {
      console.log("Sub2 " + val);
    });
 
    this.subject$.next(Math.floor(Math.random() * 200) + 1);
 
                            
                        

Subjects maintain a list of subscribers

Whenever a subscriber subscribes to a subject, it will add it to an array of subscribers. This way Subject keeps track of its subscribers and emits the event to all of them.

There are other types of subjects

What we have explained to you is a simple subject. But there are few other types of subjects. They are

  1. ReplaySubject
  2. BehaviorSubject
  3. AsyncSubject

We will talk about them in the next tutorial.