Displaying BehaviorSubject variable in Angular view is not possible

I am proud to introduce my latest service creation:

Service File :

InfoDetails=new BehaviorSubject<any>('');

captureServiceData(data: any): Observable<any> {
    return this.http.post<any>(`${environment.url}/Info`, data)
}

In component 1:

 ngOnInit(): void {
    this.fetchInfo(this.UserId);
 }
 InfoList: any;
 fetchInfo(userId)
  { 
  this.Service.captureServiceData(json).subscribe(data => {
  if (data.response == 200) {
    this.InfoList = data.response;

    let jsonData=[
      {
          "Id": 2,
          "Name": "Test",
          "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f98d9c8a8db99e94989095d79a96">[email protected]</a>",
          "Code": 4346
      },
      {
          "Id": 2,
          "Name": "Test",
          "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91e3f2e4e3a6d7f0fa76fefbb9f4f8fa">[email protected]</a>",
          "Code": 4346
      }
     ];

    this.Service.InfoDetails.next(jsonData);
   
  }
})
  }

In Component 2:

 let jsonData=[
          {
              "Id": 4,
              "Name": "Test 1",
              "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email_" data-cfemail="196d7c6a6d28597e37">[email protected]</a>",
              "Code": 43246
          },
          {
              "Id": 67,
              "Name": "Test 3",
              "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74001107004747341319">[email protected]</a>",
              "Code": 3336
          }
         ];

    this.ChatService.chatInfoDetails.next(jsonData);

My current challenge lies in finding a way to iterate through variables in component 2 so that any changes to the variable values are instantly reflected in the component without necessitating a page refresh.

If you have any suggestions or insights, I would greatly appreciate it. Thank you!

Answer №1

When you need to display content in HTML, simply follow these steps.

Create a getter for the Subject. However, I highly recommend converting the subject to an observable as demonstrated below.

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class ChatService {
  InfoDetails = new BehaviorSubject<any>('');
  InfoDetailsObservable$: Observable<any>;

  getsInfo(data: any): Observable<any> {
    return this.http.post<any>(`${environment.url}/Info`, data);
  }
  constructor() {
    this.InfoDetailsObservable$ = this.InfoDetails.asObservable();
  }
}

Next, in component 2, define the getter like this:

get infoDetails() {
    return this.ChatService.InfoDetailsObservable$;
}

Lastly, in the HTML of component 2, use the async pipe to render the most recent values of the behavior subject!

<section class="row">
  <div class="col-md-1">
    <pre *ngIf="!(infoDetails | async)">loading data...</pre>
    <span *ngFor="let test of infoDetails | async">{{ vehicle.Name }}</span>
  </div>
</section>

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

Tips for utilizing <Omit> and generic types effectively in TypeScript?

I'm currently working on refining a service layer in an API with TypeScript by utilizing a base Data Transfer Object. To prevent the need for repetitive typing, I have decided to make use of the <Omit> utility. However, this has led to some per ...

Is it possible that CSS is being impacted by DomSanitizer and Renderer2, causing issues with the flow and inheritance of styles?

As I embark on creating my own Calendar with Angular, I am faced with the challenge of utilizing innerHTML while ensuring safety measures are in place. Admittedly, I am new to this and must confess that my code may not be the most elegant. Following tutori ...

Tips for identifying the characteristics of a mobx observer in the developer console of a web browser

Within the project I am currently involved in, there is heavy reliance on dependency injection. In this context, you will come across code structures similar to the following: type BigWidget = { title: string, } const AProps = { b: BigWidget } cl ...

determine the keys of the object properties stored in an array

Is there a method to generate an array-like list of potential values consisting of object property values within an array? Here is an example object: const columns: SomeType[] = [ { name: "first", someProp: true }, { name: "second", ...

The type 'Query' does not contain an index signature that accepts a parameter of type 'string'

I've incorporated the accesscontrol npm package for RBAC (role-based access control) into my API. Below is the code I'm using to check whether a user has permission on a particular resource: export const checkUserPermission = async ( req: Reque ...

The width of Kendo Angular 2 grids pager and top header does not increase when scrolling

Our grids now have the horizontal scrolling feature enabled through CSS (kendo-grid {overflow: auto;}). However, we've noticed that the pager and top header of the grids do not expand their width when scrolling. Take a look at the screenshot below: ...

"Implementing a retry feature for Angular http requests triggered by a button

Imagine having a situation where a component has a method that triggers an http request defined in a service. The observable is subscribed to within the component: Component: fetchData() { this.apiService.fetchDataFromServer().subscribe( respo ...

Issue with tsconfig path alias not resolving when paths are outside of the baseUri

I've encountered an issue in my monorepo where the tsconfig doesn't resolve paths that are located above the current project directory. Here's an overview of my project structure: ── apps │ ├── sahl │ │ ├── index ...

The Angular application on port 4200 is displaying information using HTML, while the NodeJS server on port 8080 is showcasing data in

I am currently utilizing angular 5 along with node js to create a crud application for events data. The issue I am facing is that when I try to retrieve events data from port 4200 (http://localhost:4200/event) which is being served through angular, everyth ...

Is it possible to use optional destructured arguments in a Typescript function?

Is there a way to create a function that accepts an optional object argument using destructuring in Typescript? myFunction({opt1, opt2}?: {opt1?: boolean, opt2?: boolean}) The error message "A binding pattern parameter cannot be optional in an implementa ...

Unable to retrieve data from localStorage in Next.js

Unable to access localStorage in Nextjs. Code works as expected without errors, but the terminal throws: ReferenceError: localStorage is not defined at MainGrid (./app/components/WeightDisplay/MainGrid.tsx:17:96) 8 | // Initialize states for prefe ...

Experiencing difficulties while running the npm internationalize command

Package Details { "name": "m.zbor.md", "version": "1.0.0", "description": "Mobile version of Zbor.md website", // more package details... } Typescript Configuration { "compilerOptions": { "target": "es5", "module": "commonjs", // m ...

Encountering an issue with unexpected token 'import' while working on Angular-cli and RC

Currently, I'm in the process of setting up Material 2 with Angular-cli RC5. However, when attempting to load the material button component in app.module.ts, I encounter the following error message. zone.js:461 Unhandled Promise rejection: SyntaxErro ...

What is the process for creating a React Component with partially applied props?

I am struggling with a function that takes a React component and partially applies its props. This approach is commonly used to provide components with themes from consumers. Essentially, it transforms <FancyComponent theme="black" text="blah"/> int ...

Is there a way to verify the content inside the :before selector using Jasmine within an Angular 6 application?

Looking to test whether the content of a label changes based on the checkbox being checked using Jasmine in an Angular 6 project. Is this feasible? Code snippet: HTML <input id="myCheck" class="checkbox" type="checkbox" /> <label for="myCheck" ...

Encountering the error message: ERESOLVE unable to solve dependency tree while trying to install

I'm encountering an error when attempting to install a dependency. How can I resolve this issue? npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" cla ...

What is the best way to implement individual error handling for each function within combineLatest?

I'm looking for guidance on how to handle errors in each function within this `combineLatest` operation. Check out the code snippet below: const combined = combineLatest( this.myservice1.fn1(param), this.myservice2.fn2(), this.myservice3.fn3() ...

After upgrading to version 8 of the Firebase JS SDK, the "firestore" module (imported as "firebase") could not be located within the "firebase" package

After upgrading the firebase JS SDK from v7 to v8.0.0, I changed my import of firebase as shown below. import * as firebase from 'firebase'; However, attempting to access certain properties resulted in an error message: firebase.firestore.FieldV ...

"Unveiling the Benefits of Converting Body to JSON String and Object in Angular 7

Why is it necessary to convert event.body into a JSON string and then parse it back into an object? this.excelFileService.upload(this.currentFileUpload).subscribe(event => { if (event.type === HttpEventType.UploadProgress) { this.progress ...

Should FormBuilder be utilized in the constructor or is it considered a poor practice?

section, you can find an example of implementation where declarations for formBuilder and services are done within the constructor(). While it is commonly known that using services inside the constructor() is not a recommended practice and should be done ...