# What is a Subject in Angular ?

In 
Published 2022-12-03

This tutorial explains to you what a Subject is in Angular and also provide you with an example.

In Angular, in many cases we need to see the value(s) of a stream in real time and in the same time we need to get access to this stream to many consumers (subscribers). Each subscriber/ consumer will do different things function on the stream value(s). In this situation we have to define a Subject.

A Subject = a set/ stream of data a subscriber (consumer) can subscribe to.

When we are defining a Subject, the subscriber can see the NEW data in the stream, starting from subscription time. You cannot see the last data in the stream. If you want to see the last value of the stream you have to use BehaviorSubject in Angular. It might be useful for you to take a look at the following articles as well: ReplaySubject in Angular and AsyncSubject in Angular.

In order to use this feature, you have to import "Subject" from 'rxjs' or 'rxjs/Subject' into the component that use it:

import { Subject } from 'rxjs';

Here is the code we used for showing Subject behavior in Angular 4:

import { Component } from '@angular/core';
import { Subject } from 'rxjs/Subject';
 
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
 
  products = [
    {name:"apples", price:10, onStock:"Y"},
    {name:"bananas", price:5, onStock:"Y"},
    {name:"tomatoes", price:11, onStock:"Y"}
  ];
 
  ngOnInit() {
 
    console.log('SUBJECT:');
    let subject2 = new Subject<number>();
 
    let subscription21 = subject2.subscribe( var1  => {
      console.log('subscription21 /'+var1+'/');
    });
    console.log('-----------------------------------');
    subject2.next(1);
 
    let subscription22 = subject2.subscribe( var2  => {
      console.log('subscription22 /'+var2+'/');
    });
    subject2.next(2);
    console.log('===================================');
 
  }
}

And here is the result in the browser console: