Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 8223

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T11:07:06+00:00 2024-11-28T11:07:06+00:00

Data Sharing using Services in Angular

  • 60k

Michael started his angular project with two components. He used input decorator to pass data from parent to child component and output decorator to pass data from child to parent component. As the project grew, he kept adding more components to the project and before he knew it, the project was as big as the “Fast and Furious” franchise.
Now his project has a hierarchy of 10 levels and if he wants to pass data from top component to the bottom most, he has to pass the data through all the 10 components. Michael is sad about his work and he knows there is a better way to do this. Lets help him to clean his project.

Michael can use Services to solve this problem and share data between components which are not directly related. So instead of directly passing data from one component to another, we will make a middleware service and use that as a bridge.

We will use Observable to create a Pub-Sub mechanism in a service in our application. Let’s say if component A wants to update a data, it will publish the data to the service and component B wants to get the data value whenever it value is updated then it will subscribe to that data and will receive updates on value change.

I am attaching the Code snippet for publisher, subscriber and the middleware below. I have also created a video tutorial on the same which you can see on the YT channel here.

The middleware where any component can publish and any other component can listen to data updates.

import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs';  @Injectable({     providedIn: 'root' }) export class DataServiceService {      private _dataStream = new BehaviorSubject("");     constructor() { };      getDataStream() {         return this._dataStream.asObservable();     }      putDataToStream(data: string) {         this._dataStream.next(data)     }  }  
Enter fullscreen mode Exit fullscreen mode

This is how component can publish data to the middleware.

import { Component, OnInit } from '@angular/core'; import { DataServiceService } from '../../../../services/data/data-service.service';  import * as categorydata from './category.data.json';  @Component({     selector: 'app-category',     templateUrl: './category.component.html',     styleUrls: ['./category.component.scss'] }) export class CategoryComponent implements OnInit {      categories: any[] = (categorydata as any).default;     categoryName: string = "This is Category Component";     constructor(private dataService: DataServiceService) { }      ngOnInit(): void { }      changeVariable(e: string) {         this.categoryName = e;     }      publishData() {         this.dataService.putDataToStream('Data Published form Category');     }  }  
Enter fullscreen mode Exit fullscreen mode

This is how component can subscribe to the middleware and gets the update.

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { DataServiceService } from '../../services/data/data-service.service';  @Component({     selector: 'app-card',     templateUrl: './card.component.html',     styleUrls: ['./card.component.scss'] }) export class CardComponent implements OnInit {      @Input() data: any = {};     @Output() passName = new EventEmitter();     serviceData: string = "";      constructor(private dataService: DataServiceService) {         const data = this.dataService.getDataStream();         data.subscribe({             next: (data: string) => {                 this.serviceData = data;             },             error: (err: any) => {                 console.log(err);             }         })     }      ngOnInit(): void { }  }  
Enter fullscreen mode Exit fullscreen mode

Thanks for reading, Happy Koding everyone!!!

angularjavascriptservicewebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.