Tips for transferring information between components using observables and showcasing the data in a different HTML template within Angular

Hey there! I'm currently facing a challenge where I need to pass an object from the 1st Component to the 2nd Component upon a click event. My approach involves using a data service with set and get functions:

Data Service

@Injectable({
  providedIn: 'root'
})
export class DataService{

 private subject = new Subject<any>();

 setObject(obj) { 
  this.subject.next(obj) 
 }

 getObject(): Observable <any> {
  return this.subject;
 }
}

In the 1st Component, I call the setObject(obj) method on a click event.

Parent Component HTML

<tbody>
 <tr *ngFor="let item of tableElements;" (click)="onSelect(item)">
 ...

1st Component

export class ParentComponent {

 constructor(private dataService: DataService) { }

 onClick(obj: object) {
    this.dataService.setObject(obj);
 }
}

Now, in the 2nd Component, I am unsure about how to correctly subscribe to the Observable and display the object without just saving it to another variable directly. I have come across suggestions that discourage manipulating the observable that way.

2nd Component

export class ChildComponent {
  displayedObject$: Observable<any>;

  constructor(private dataService: DataService) {
    this.displayedObject$ = dataService.getObject().pipe(
      map((res) => {
        console.log('value from data service' + res);
        return res;
      })
    );
  }
}

So, how can I properly showcase the object and its properties in my HTML template? I have already attempted:

Child Component HTML

<div> Value from Data Service = {{ displayedObject$ | async }} </div>

Although the console displays the object, unfortunately, it doesn't reflect in the template. Any insights on what could be going wrong?

Answer №1

This example demonstrates how to set up an observable in a basic service and then subscribe to it from another component.

Once the value is received from the observable, you can display it in the calling component's HTML template using an async pipe observable.

Service

TS

@Injectable()
export class Service {
  subject: Subject<number> = new Subject();

  setDataObject(obj) { 
    this.subject.next(obj); 
  }
  
  getDataObject(): Observable<any> {
    return this.subject; 
  }
}

Client Component

TS

In this code snippet, we initialize the asynchronous observable without subscribing to it and provide a method to set the value of the observable within the service with a random number.

export class AppComponent {
  displayObservable$: Observable<number>;

  constructor(private api: Service) {

  this.displayObservable$ = api.getDataObject().pipe(
      map((res) => {
        console.log('value from service = ' + res);
        return res;
      })
    );
  }

  sendValue(val: any) {
    let num: number = Math.floor(Math.random() * 100);
    console.log('value sent to service = ' + num);
    this.api.setDataObject(num);
  }
}

HTML

The following HTML contains a button to dispatch a value to the service and an async observable to display the response:

<div>Value from service = {{ displayObservable$ | async }}</div>

<p>
  <button
    type="button"
    class="btn btn-primary"
    id="btnSendValue"
    (click)="sendValue($event)">
    Send a value to service
  </button>
</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Maximizing the versatility of components with styled-components and React: A comprehensive guide to incorporating variants

Currently, I am a novice programmer working on a personal project using React for the front-end. I am looking to create a Button component with the styled-components package that can be easily reused throughout the app with some variations in size, color, ...

Having trouble loading my app.js in Angular - Seeking help on Coursera!

I've followed the instructions provided thus far and inserted the HTML code accordingly. However, upon attempting to load the page, all I see is: The tabs: The Menu Appetizers Mains Desserts The description: image: dish.name , dish.name , dish.labe ...

Counting JSON data items in Ionic2 can be achieved by iterating through the object

Encountering a new issue, I need to tally @NAME in order to populate array FACET[] and display @KEY Myjson " RESULT":{ "FACET":[ { "@NAME" : "creator", "@COUNT" : "20", "FACET_VALUES ...

`The resurgence of CERT_FindUserCertByUsage function in JavaScript`

I am currently grappling with unraveling the connection between C++ dlls and JavaScript. There is a snippet of js code that reads: cert = CERT_FindUserCertByUsage(certDB, certName.nickname,certUsageEmailSigner, true, null); where the variable cert is ini ...

Creating a smooth fading effect for an element within a react component

I am currently working on implementing a fade out warning/error message (styled with Bootstrap) in a React component, however, I am encountering some challenges with the timing of the fade-out effect. Up to this point, the fade out effect is functioning c ...

AngularJS version 1.5.11 experiencing issues with ng-repeat functionality

Having an application built on angularJS v1.5.11, I encountered a major issue while attempting to use ng-repeat in a table format like below: <tbody> <tr ng-repeat="score in data.result"> <td ng-repeat="item in score"> {{ item }} & ...

Navbar not displaying output in React JS

I followed a tutorial on YouTube to create a navbar using Bootstrap and React, but I'm facing issues with the output. The YouTube tutorial used HTML along with Bootstrap to make the navbar. Even though the classes are similar, all I can see is a small ...

AngularJS ng-repeat doesn't refresh following an Ajax request

I am using an AngularJS application where I have a chat feature on the right side for communication with my clients. Here is the HTML code: <div class="recent" ng-show="show_chat_list"> <h2></h2> <div ng-repeat="customer in r ...

Incorporating JSON data seamlessly into a visually appealing Highcharts pie chart

It seems like I'm facing a minor issue here. Everything was working fine until... $(document).ready(function() { // Original data var data = [{ "name": "Tokyo", "y": 3.0 }, { "name": "NewYork", "y": 2.0 }, { "name": "Berlin", ...

Resolving the Error: "Type 'Customer | undefined' is not compatible with type 'Customer'" in Angular

I encountered an issue with the following code: ... export class ListCustomersComponent implements OnInit { customers: Array<Customer> = []; showCustomer?: Customer; isSelected: boolean = false; deletedCustomer?: Customer; returnedMessa ...

The results of MongoDB aggregation queries consistently yield null values

Here is the initial query: [{ $match: { $and: [ {campaignID: "12345"}, {date: "2016-10-18"}, {hour: {$gte: 0}}, {hour: {$lte: 3}} ] ...

What is the best way to eliminate an event listener from a DOM element?

Looking for help with toggling add/remove event listeners on click. Can anyone provide suggestions to improve my code? I've searched through various solutions on Stackoverflow without success. This educational tool involves rotating the center cube ...

An effective method for cutting off text while preserving HTML styling using jQuery

Is there a way to truncate text using jQuery while preserving the HTML formatting? I attempted the code below, but it doesn't maintain the HTML tags. var truncate = function() { $('p.truncated').text(function(index, oldText) { if (old ...

What could be causing my Angular code to submit back unexpectedly?

My goal is to make an initial call to the database to populate some dropdowns, after which all actions are done through AJAX. However, whenever I click a button on the page, it seems to be posting back and calling the function that fetches dropdown values ...

Using Laravel to Toggle Element Visibility Based on Role in VueJS

<NavLink v-if="value":href="route('accounts')" :active="route().current('accounts')"> Accounts Here is a scenario I encountered: within my user database, there are designated roles as either User or ...

What is the solution for resolving the Angular error 'Cannot read property "_co.x" of undefined'?

Currently, I am facing an issue with nested JSON objects on a form that sends data to a database. Despite trying the *ngIf statement as recommended in Angular 5 - Stop errors from undefined object before loading data, the view does not update even after th ...

Adding an active class to a selected list item can easily be accomplished by targeting the

Hey there, I'm attempting to apply a class to the selected list item and also add a class when scrolling to a specific div. For instance, if I scroll to div#six, the number six (6) in the menu should also have the 'active' class. [Check out ...

How can you form a promise by combining multiple asynchronous file reads in Node.js?

Consider the following scenario: fn1() { [filepath1, filepath2, ..., filepathN].forEach(process); function process(path) { fs.readFile(file, translate); } } The callback function translate operates on the contents of each file. How can ...

A SyntaxError was encountered because functions in strict mode code must be declared either at the top level or directly within another function

Hey there, I'm encountering a strange issue with my project. Everything runs smoothly when I run it in Developer mode using `grunt server`. However, when I try to run it in production mode with `grunt build`, I encounter an error: Uncaught SyntaxEr ...

What is the best way to utilize regex in converting this CSS block to LESS?

Currently undertaking the task of refining over 10,000 lines of CSS code. Instead of manually converting line by line, I aim to transform from this: -webkit-transition: .1s linear all; -moz-transition: .1s linear all; transition: .1s linear all ...