banner



How To Use Data From Component In Service

Sharing Information between Components using Service in Angular

Sharing information between components can be sometimes becomes difficult.

As yous need to update information on click events from 1 component and go data from another component and then reflecting the changes on same component.

In this tutorial nosotros will acquire how to share data between components using a Service, to exist more specific how nosotros tin bear witness notifications for component communication in DOM using a Snackbar module from Athwart Material UI component library. We will learn concept of Subject field and how we can use it for components communication.

You can find link to full lawmaking at the cease of this article.

Let'south say nosotros have 2 components Message Component and Output Component that may or may not be related, they can exist parent, child, siblings or not at all related only they share a aforementioned instance of service.

Goal

We want to ship notifications from Bulletin Component to Output Component or any other component. This is the last goal we desire to achieve.

Goal

We cannot use EventEmitter class equally component may not exist related and as well if they are related there is a lot of hierarchy we need get through which makes code difficult to maintain. Instead nosotros will be using special type of Observable Known as Subject.

A subject field is an Observer and an Observable, in simple words a field of study involves taking the notifications from single source and forwarding them to one or more than destinations. A subject field is commonly placed in a Service.

The output Component will send the variable value truthful to the Discipline and Subject field will update this variable from false to true in the Message Component and the notifications volition be shown in the output component.

Outset, We will create a new Angular Project and and so add Angular Material UI component Library for cute User Interface and apply Snackbar module to testify notifications. We will create Message Component and a Message Service and app Component(Default) will act equally Output Component.

Last Result will look similar:

Let's Dive into Code!

We will create a new angular projection for that and make use of angular-cli for this project. Make sure you have already installed node and npm on your auto. Open Command Prompt(cmd) and navigate to the desired location. Enter the following command in cmd.

          ng new share-messagee-between-components        

Include Angular Material UI component Library in your Angular Project for beautiful User Interface. It will ask for some user input, but y'all tin can but press Enter.

          ng add @angular/material        

Creating Message Component

Nosotros volition create Bulletin component using angular-cli. To generate new component type post-obit control:

          ng g c Message        

Creating Message Service

Now we will create new Message Service using angular-cli. To generate new Service type following control:

          ng g s Bulletin        

Creating Subject in Service

First stride is to create a subject and expose discipline equally an observable in the service. A subject act every bit an source from where the notifications are sent to other components.

          private _successMsgSource = new Subject area<boolean>();        

Next we expose Subject equally an Appreciable. The right convention for declaring observable is to append a $ sign

          successMsg$ = this._successMsgSource.asObservable();        

And so creating a method which accepts the value from the Output Component and pushes that value using an observble.

          sendSuccessMsg(bulletin: boolean) {          this._successMsgSource.adjacent(message);          }        

Complete service.ts file

                      import            { Injectable }            from            "@angular/core";                      import            { Subject area }            from            "rxjs";          @Injectable({          providedIn: "root",          })                      consign            course MessageService {          constructor() {}          private _successMsgSource = new Subject<boolean>();          successMsg$ = this._successMsgSource.asObservable();          sendSuccessMsg(message: boolean) {          this._successMsgSource.next(message);          }          private _errorMsgSource = new Subject<boolean>();          errorMsg$ = this._errorMsgSource.asObservable();          sendErrorMsg(message: boolean) {          this._errorMsgSource.side by side(message);          }          private _uploadedMsgSource = new Subject<boolean>();          uploadedMsg$ = this._uploadedMsgSource.asObservable();          sendUploadedMsg(message: boolean) {          this._uploadedMsgSource.side by side(bulletin);          }          private _uploadFileExistMsgSource = new Subject field<boolean>();          uploadFileExistMsg$ = this._uploadFileExistMsgSource.asObservable();          sendUploadFileExistMsg(bulletin: boolean) {          this._uploadFileExistMsgSource.next(message);          }          }        

Sending Value from Output Component to service

2nd step is to send bulletin from Output Component to the service. Now we send notifications on clicking of button and call different methods. We will also call "openSnackBar()" method to open a Snackbar on push click.

Complete app.component.html

          <mat-menu>          <h1>Sharing Messages Data betwixt Components</h1>          <div>          <push button          mat-raised-button          colour="primary"          (click)="openSnackBar()"          (click)="successMsg()"          >          Success Message          </push button>          <button          mat-raised-button          colour="primary"          (click)="openSnackBar()"          (click)="errorMsg()"          >          Error Message          </button>          <push button          mat-raised-push button          colour="primary"          (click)="openSnackBar()"          (click)="uploadFileExistMsg()"          >          File Exist Bulletin          </button>          <button          mat-raised-button          color="primary"          (click)="openSnackBar()"          (click)="uploadedMsg()"          >          Upload Bulletin          </button>          </div>          </mat-bill of fare>        

Allow'south define this methods in class. The methods volition call sendSuccessMsg() from the Bulletin Service and passing the argument true to the method.

We will Inject Service in the constructor of the component. Also we will Inject MatSnackBar Module. Also import the service MatSnackBar too.

Complete app.component.ts File

                      import            { Component, OnInit }            from            "@angular/cadre";                      import            { MessageService }            from            "./services/message.service";                      import            { MessageComponent }            from            "./bulletin/message.component";                      import            { MatSnackBar }            from            "@angular/cloth";          @Component({          selector: "app-root",          templateUrl: "./app.component.html",          styleUrls: ["./app.component.scss"],          })                      export            class AppComponent implements OnInit {          title = "share-messagee-between-components";          ngOnInit() {}          durationInSeconds = i;            //Snackbar duration in seconds to be shown on screen                    constructor(          individual _snackBar: MatSnackBar,          private _msgService: MessageService          ) {}                      //Snackbar Method                    openSnackBar() {          this._snackBar.openFromComponent(MessageComponent, {          duration: this.durationInSeconds * 1000,          });          }                      //Message Methods sending the variable value to service                    errorMsg() {          this._msgService.sendErrorMsg(true);          }          successMsg() {          this._msgService.sendSuccessMsg(truthful);          }          uploadedMsg() {          this._msgService.sendUploadedMsg(truthful);          }          uploadFileExistMsg() {          this._msgService.sendUploadFileExistMsg(true);          }          }        

Adding Styling

Adding Basic Styling to the Component:

Consummate app.component.scss file

          h1 {          text-align: middle;          }          mat-card {          flex-management: column;          margin: 1rem;          width: 70vw;          background-color: #f2f5f7;          display: flex;          height: 50vh;          justify-content: space-betwixt;          div {          display: flex;          justify-content: space-evenly;          align-items: middle;          }          mat-carte du jour-deportment {          margin-lesser: 0;          }          }        

Annotation: If an error occurs during the compilation of code add together below line of lawmaking in app.module.ts file

          providers: [],          bootstrap: [AppComponent],          entryComponents: [MessageComponent],        

Subscribing to the Observable

The Final Stride is to subscribing to the observable in the Message Component. And so head over to message.component.ts file and since we are making use of Subject field asObservable that is defined in the service, so allow's begin by injecting Service. Likewise make certain to import it.

                      import            { MessageService }            from            "../services/message.service";          constructor(private _msgService: MessageService) {}        

Generally we subscribe to observable in the OnOnit Lifecycle Hooks

          ngOnInit() {          this._msgService.successMsg$.subscribe(          (message) => (this.successMsg = message)          );        

Updating the value of successMsg variable from false to true when a method is called.

Complete message.component.ts file

                      import            { Component, OnInit }            from            "@angular/core";                      import            { MessageService }            from            "../services/bulletin.service";          @Component({          selector: "app-bulletin",          templateUrl: "./message.component.html",          styleUrls: ["./message.component.scss"],          })                      export            class MessageComponent implements OnInit {          successMsg: boolean = false;          errorMsg: boolean = false;          uploadedMsg: boolean = faux;          uploadFileExistMsg: boolean = faux;          constructor(private _msgService: MessageService) {}          ngOnInit() {          this._msgService.successMsg$.subscribe(          (message) => (this.successMsg = message)          );          this._msgService.errorMsg$.subscribe(          (message) => (this.errorMsg = message)          );          this._msgService.uploadedMsg$.subscribe(          (bulletin) => (this.uploadedMsg = message)          );          this._msgService.uploadFileExistMsg$.subscribe(          (bulletin) => (this.uploadFileExistMsg = message)          );          }          }        

Now we call variable in DOM and only show a particular notification when the value of that variable is set to true using *ngIf directive.

Complete message.component.html file

          <span grade="case-pizza-political party">          <div class="successMsg" *ngIf="successMsg">Message sent successfully</div>          <div grade="errorMsg" *ngIf="errorMsg">Something went wrong</div>          <div form="uploadedMsg" *ngIf="uploadedMsg">Files Uploaded successfully</div>          <div class="uploadFileExistMsg" *ngIf="uploadFileExistMsg">          File already exists. Please choose a different File.          </div>          </bridge>        

Calculation Styling

At present we will testify dissimilar colors for different messages i.e for success message — dark-green, error message — cerise etc.

Complete bulletin.component.scss file

          .successMsg,          .uploadedMsg {          colour: dark-green;          }          .errorMsg,          .uploadFileExistMsg {          color: cherry;          }        

Output

You can find the total source code on

Download source lawmaking on: GitHub🚀

Test information technology live on: Stackblitz🚀

Angular

RxJS

Your feedback is welcome!

If you enjoyed this article, please clap for it or share it. Your help is always appreciated.

Responsive Animated Navbar

Create a React-Native Chart

File Upload Component with Resumable Functionality

How To Use Data From Component In Service,

Source: https://medium.com/@hitensharma1515/sharing-data-between-components-using-service-2d662a653a89

Posted by: joneswabiagre.blogspot.com

0 Response to "How To Use Data From Component In Service"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel