I am not an engineer
Must read:Is there a real future in data analysis for self-learners without a math degree?

Angular 4: What is a Subject and how it can be used (basic example)?

Are you using observables and observers on your discovery of Angular 4? Here is a brief example of how to use the Subject, which combines both.

  • A subject is an observable and an observer at the same time.
  • It comes with the RxJS package.
  • It can be used in a powerful association with a service.
  • Example:
    • This example worked for me with the following versions:
      • OS Win32 x64
      • node 6.9.1
      • Angular/core: 4.2.4
    • Problem: we need to listen to an event in component A and react to it in component B.
    • Three-fold solution:
      • We set up service 1, which offers a Subject object.
      • The Subject of Service 1 is used in component A to emit an event.
      • The Subject of Service 1 is used in component B to listen to the event.
    • NB: this solution also applies to a case where the event can be emitted or observed in any number of components.
    • Step 1: We set up the service
      • Create a typeScript file for the service (e.g. “myservice.service.ts”)
      • Make the necessary imports :
        //Modules:
        import { NgModule } from '@angular/core';
        //ReactiveX
        import "rxjs/Rx";
        import { Subject } from "rxjs/Subject";
        export class MyService {
        public mysubject : Subject = new Subject();
        }
      • Import and provide the service in app.module.ts :
        • import { MyService } from ‘./services/myservice.service’; //my sweet service
          @NgModule({providers: [ MyService ]})
    • Step 2: We connect to the service in component A:
      • Import the service:
        • import { MyService } from './services/myservice.service';
      • Instantiate the service in the constructor:
        • constructor(private myservice: MyService) {}
      • Emit a value wherever needed in your code:
      • You can insert it in the constructor, the ngOnInit or any other function
        • myservice.mysubject.next("My favourite value");
    • Step 3: We connect to the service in component B:
      • Import the service:
        • import { MyService } from './services/myservice.service';
      • Instantiate the service in the constructor:
        • constructor(private myservice: MyService) {}
      • Listen to the service wherever needed in your code:
        • You can insert it in the constructor, the ngOnInit or any other function:
          • this.myservice.mysubject.subscribe( (value) => {
            //insert your code here
            });
    • Step 4: Make sure the subscription is executed before the first emit
      • Insert console logs before each step and check if the logs come in the right order : setup of the service, setup of listening, event emission

Leave a Reply

Your email address will not be published. Required fields are marked *