Tips for utilizing an observable in Angular without subscribing to it

I am currently working on an Angular 8 application that involves making API calls. Here is an example:

getDossierEntry(patientUUID: string, type: String = ''): Observable<DossierEntry[]> {
  const entryType = type === '' ? 'all' : 'type/' + type;
  return this.http.get<DossierEntry[]>(`${this.baseUrl}/${patientUUID}/DossierEntry/` + entryType);
}

In addition, I have a parent component structured like this:

export class DossierCorrespondenceComponent implements OnInit {

  correspondenceEntries$: Observable<DossierEntry[]>;

  @Input() allCorrespondence: Array<DossierEntry>;
  @Input() correspondenceEntries: Array<DossierEntry>;
  @Input() attachmentEntries: Array<DossierEntry>;

  message = '';
  emptyMessageCorrespondentie = 'Geen correspondentie.';
  errorMessageConnection = 'Er ging iets mis met de connectie. Probeer over enkele minuten nogmaals.';

  correspondenceLoaded = false;

  showingSingle = false;

  single: DossierEntry;

  
 // Rest of the code for DossierCorrespondenceComponent

}

The HTML template associated with the parent component looks like the following:

<app-vital10-page [noTopBar]="true">
  <h2 class="dossier-page-header">Correspondentie</h2>

  // Other elements in the template

</app-vital10-page>

// Rest of the HTML code related to the parent component

Subsequently, there is a child component defined as follows:

export class DossierCorrespondenceListComponent implements OnInit {

  @Input()
  correspondenceEntries: DossierEntry[];

  @Input() showingSingle;

  constructor() { }

  ngOnInit() {
    // Initialization logic here
  }

}

And the corresponding HTML template for the child component is structured like this:


<div *ngIf="!showingSingle && correspondenceEntries && correspondenceEntries.length > 0;">
  <div class="main-row main-row-dossier">
    // Additional HTML content for the child component view
  </div>
</div>

// Rest of the HTML code specific to the child component

However, despite the correct data being retrieved, the child component data does not appear in the parent component view. This may be due to the usage of observables and subscription methods within the components.

If you are seeking a way to streamline this process without direct subscriptions, consider revisiting the data flow architecture between the parent and child components.

Thank you for your attention.

Answer №1

To achieve what you are looking for, you can make use of the as keyword in the *ngIf directive like this:

...
<ng-container *ngIf="(correspondenceEntries$ | async) as correspondenceEntries">
  ...
  <app-dossier-correspondence-list [correspondenceEntries]="correspondenceEntries" ></app-dossier-correspondence-list>
  ...
</ng-container>
...

With the as keyword, the value emitted by the Observable is stored in the variable specified after it. Currently, the as keyword is only available within the *ngIf directive in Angular 8, so you must use *ngIf even if you don't necessarily need conditional template rendering.

Check out this StackBlitz Example for reference.

Answer №2

My solution to the problem is as follows:

<ng-container *ngIf="correspondenceEntries">
    <app-dossier-correspondence-list [correspondenceEntries]="correspondenceEntries"> </app-dossier-correspondence-list>
  </ng-container>

  <ng-container *ngIf="attachmentEntries">
    <app-dossier-correspondence-attachments
      [attachmentEntries]="attachmentEntries"
    ></app-dossier-correspondence-attachments>
  </ng-container>

I appreciate all of your hard work and help on this issue.

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 altering the appearance of a dropped item using JQueryUI sortable

I have a straightforward website where I need to implement the ability to drag and drop styled DIV elements between two containers. Utilizing JQueryUI's sortable function, this behavior was successfully achieved with the following code: $("#active-co ...

Customize the appearance of every other column in an asp gridview

Looking for help with formatting rows and columns in an ASP GridView. The rows are automatically colored alternating, and I want to make the content in every first column bold and every second column normal. I have heard about using CSS nth-child() to achi ...

Utilizing ES6 imports with module names instead of paths

Is there a way to import modules using just their name without the full path? For instance, can I simply use: import ViewportChecker from 'viewport-checker'; instead of import ViewportChecker from '../ViewportChecker'; I'd ...

I'm interested in learning more about how to select or deselect all checkboxes

How can I uncheck the "all" checkbox when I uncheck another checkbox? $('#All').click(function () { var status = $(this).is(":checked"); if (status) { $.each($('input[name="checkbox"]'), function () { this. ...

Unable to access static library Java Script file path using NSBundle

I have integrated a static compiled library into my project, which includes a JavaScript resource. At a specific event in my app, I need to execute the JavaScript file from this library. However, I am facing an issue where the path to the JS file appears ...

Why are my cursor and my drawing line on opposite sides?

I've been working on a JavaScript drawing app, but I'm facing an issue where the drawn elements are not aligned with my cursor. The positioning seems off, especially when moving to the right or up on the canvas. As I move towards the furthest lef ...

How can I update information based on the chosen option in a select dropdown using Vue?

I have a chart displayed in my user interface that needs to be updated based on the selected time period. By default, the chart displays data from the past year, but when the user selects "Month," it should show data from the past month. <div cla ...

Retrieving child elements from parent identifiers using Typescript

I've been working on creating a new array with children from the data fetched from my database. While my initial attempt was somewhat successful, I believe there are some missing pieces. Could you assist me with this? Here is the raw data retrieved f ...

Applying Styles to Cells Using the Google Sheets API (v4)

Having encountered an issue while using the Google Sheets API (v4) for programmatically creating or updating spreadsheets, I have come across the following problem: According to the documentation (https://developers.google.com/sheets/api/reference/rest/v4 ...

Optimizing Angular: Configuring baseHref for assets during development with SSR

During production, we set the base href using the following command: ng build --base-href /app/ This configuration works smoothly as our assets are also accessible at /app/assets/, just as expected. However, I have been facing difficulties achieving the ...

Modify parent component state when input in child component changes in React

I am working on a parent component called NewPetForm: class NewPetForm extends React.Component { state = { name: '', age: '', animal: '', breed: '' }; render() { ...

Make sure to wait for the current operation to finish before moving onto the next one

In the primeData function within the datacontext, four queries are made to a back-end Web API service: function primeData(forceRefresh) { return (getLookups(forceRefresh) // this needs to complete before moving on .then(success)) ...

Tips for matching the width of tooltips with the length of the title

I am trying to adjust the width of the antd tooltip to match that of the title. Here is the code snippet: <Tooltip placement="top" align={{ offset: [0, 10] }} title='this is the title'> <span>tooltip</span> </T ...

Creating Angular Components Dynamically through API Requests

Generating Component Template and Typescript Code Dynamically I am attempting to dynamically create a component where an HTTP service call provides us with the HTML template and Typescript code. While we can set the HTML template dynamically, I am facing ...

Stop ngOnChanges from being triggered after dispatching event (Angular 2+)

In Angular 2+, a custom two-way binding technique can be achieved by utilizing @Input and @Output parameters. For instance, if there is a need for a child component to communicate with an external plugin, the following approach can be taken: export class ...

Prevent ng-click functionality from activating when clicking on a link inside an external element

I am facing an issue on my website using ui-router. I have a table with ng-click set on the cells, but there are links inside the cells as well. My goal is to disable the ng-click when the link is clicked. <div ng-click="click()" style="background: #d3 ...

Elegant Box 2 - Ascending to the top when clicked

I am excited to share that I am using FancyBox for the first time in my project. This time, I decided to separate the image from the link for a unique user experience. The hover effect works perfectly fine - the issue arises when the link is clicked and th ...

What steps can be taken to make the carousel inconsistent when relying on the assigned id in props?

I recently developed a slider with slots, but encountered an issue. The code for this component revolves around the use of IDs for each slide as prop, making it unnecessarily complex. I am convinced that there is a more straightforward way to achieve the s ...

Tips for adding multiple fields to an element in an array using the useState hook

const[formData, setFormData] = useState({ field1 : [{ f1: "", f2: "", }], field2: [{ f3: "", f4: "", }] }) How can I efficiently update and add new elements to both field1 and field2 in the above code snippet? ...

Ways to adjust the position of a DIV based on its index value

I'm currently working on a unique project that involves creating a triangular grid using HTML and CSS. The challenge I am facing is offsetting each triangle in the grid to the left by increasing amounts so they fit seamlessly next to one another. Righ ...