The async pipe is failing to function properly when used with the same observable

I'm facing an issue with the async pipe in my view as it's not loading any data dynamically.

On my page, I need to change observable values multiple times such as reloading the page, loading more values, and updating news content based on different categories of news.

Despite trying ChangeDetectorRef and detectChanges(), I'm still unable to get it working.

ngOnInit() {
   if (this.isFirstRun) {
     this.items$ = this.apiService.getNewsByCategory(
                  this.categoryId = (this.categoryId === 0 ? 1 : this.categoryId));
     this.cg.detectChanges();
   }
 }

//NgOnChanges

ngOnChanges(changes: SimpleChanges) {
if (this.isFirstRun) {
  const chg = changes.categoryId;
  this.items$ = this.apiService.getNewsByCategory(chg.currentValue);
  this.cg.detectChanges();
}

}

// In the views i used these things

<div *ngIf="(items$| async) as news ; else loading">
// View stuff here

</div>

The items$ should reload whenever there is a change detected, specifically when the CategoryId changes. Unfortunately, it's not functioning correctly in this scenario.

Surprisingly, ngOnInit is working without any issues.

I would greatly appreciate any assistance as I'm currently drawing a blank on finding a solution.

Answer №1

A more efficient approach to solving your issue is to utilize a separate subject as a trigger, eliminating the need for manual change detection in order for the async pipe to function properly.

  refreshItems$ = new Subject()

  items$ = this.refreshItems$.asObservable().pipe(
    switchMap(param => this.apiService.getNewsByCategory(param)))
  constructor() { }
  ngOnInit() {
    if (this.isFirstRun) {
      this.refreshItems$.next()
    }
  }

  ngOnChanges(changes: SimpleChanges) {
    if (this.isFirstRun) {
      this.refreshItems$.next(changes.categoryId)
    }
  }

Answer №2

In the event that the standard change detector does not pick up on your modification, it will not trigger the ngOnChanges method. In this scenario, you have the option to manually verify for any alterations by utilizing ngDoCheck.

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 troubleshooting the error that occurs during the ng build --prod process

After creating an app, I attempted to build it using ng build --prod, only to encounter an error message related to the current version of Syncfusion. Below is the specific error I am experiencing: ERROR in ./node_modules/@syncfusion/ej2-angular-dropdown ...

The Typescript generics are unable to be assigned to type T

Take a look at my code snippet: interface IDoc { doSomething(): void } class IDocFoo implements IDoc { doSomething(): void { console.log('Do doSomething'); } } class IDocFactory { getIDocInstance<T extends IDoc>(): T { re ...

Utilizing ResolveComponentFactory() with a String Key: A Step-by-Step Guide

My goal: I want to find a way to use something similar to the "resolveComponentFactory()", but with a 'string' identifier to obtain Component Factories. Once I have them, I plan to utilize the "createComponent(Factory)" method. Check out this P ...

Undefined Perception

Trying to obtain values from an observable, my subscription code within the component looks like this: this.checkoutService.getDisabledDate().subscribe (dates=>{this.formattedDate=dates}, (error:any)=>{console.log(error)}); When logging this.forma ...

IOS 10.3.3 dilemma: Screen flickering problem plaguing an ionic/cordova application

I'm currently developing a hybrid app using angular on ionic/cordova frameworks. The app works well on android devices, but when I run it on an iPad, there is some screen flickering happening. I've tried searching online for a solution or the cau ...

Tips for refreshing the appearance of a window in angular when it is resized

I have a chat feature integrated into my application. I am looking to dynamically resize an image within the chat window when the width of the window falls below a certain threshold. Is there a method available to modify the CSS style or class based on the ...

Strategies for setting the output value for a defined generic type

Is there a way to create a function that accepts optional properties common across different types, while also requiring specific properties based on the generic type passed in? type Diff<T, U> = T extends U ? never : T type DiffTypes<T, U> = ...

Issue regarding custom CSS implementation in Angular project

Being a French speaker, I apologize in advance for any mistakes I might make. I am also fairly new to Angular, so if you could provide detailed explanations in your responses, it would be greatly appreciated. Thank you. I am trying to import a custom CSS ...

Resetting the input value for the typeahead component is currently not feasible

When using the typeahead component, it appears that clearing the input value after the results list is displayed is not possible. However, if the results list does not appear, the model can be cleared without any issues by using a button. Here are the ste ...

How can I specify a "router" member variable in Angular?

In Angular 9, I am working on a parent component where I need to pass a function to a child component. Specifically, I want to pass the "onNavigate" function to the child component... import { Router, ActivatedRoute } from '@angular/router'; ... ...

Uh-oh! An unexpected type error occurred. It seems that the property 'paginator' cannot be set

I am developing a responsive table using Angular Material. To guide me, I found this helpful example here. Here is the progress I have made so far: HTML <mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder ...

Enhancing Styled Components in Material-UI with custom props and themes using Typescript

I am exploring the use of the Material UI styled components API to incorporate both a custom theme and some props into a specific custom element. Although I have managed to get either a custom theme or props working individually, I am struggling to make t ...

React-hook-form does not display the input length in a custom React component

Introducing a custom Textarea component designed for reusability, this basic textarea includes a maxlength prop allowing users to set the maximum input length. It also displays the current input length in the format current input length/max length. While ...

The Angular Button fails to display when all input conditions are met

I'm currently working on validating a form using this link. The requirement is simple - when an input field is invalid, the `save` button should be disabled. Conversely, when all input fields are valid, the `SAVE` button should be enabled/shown. The & ...

Constructing a Primeng MessageService causes a blank webpage to appear

After downloading the QuickStart CLI of PrimeNG for Angular, I added a second component for a chart that was already included in the UI components. Everything seemed to be set up correctly, but when I saved, I ended up with a completely blank page for the ...

Troubleshooting a CORS problem with connecting an Angular application to a Node server that is accessing the Spotify

I am currently working on setting up an authentication flow using the Spotify API. In this setup, my Angular application is making calls to my Node server which is running on localhost:3000. export class SpotifyService { private apiRoot = 'http://lo ...

In the else-branch, a type guard of "not null" results in resolving to "never."

After creating a type guard that checks for strict equality with null: function isNotNull<T> (arg: T): arg is Exclude<T, null> { return arg !== null } Testing it showed that the then-branch successfully removes null from the type. const va ...

Angular 13.0 version is experiencing issues when trying to run the "ng serve" command

After installing the npm module, I encountered a problem while using node.js version 14.17.6. I am a beginner in Angular and struggling to find a solution due to not using the latest Angular CLI version. Any help would be greatly appreciated. Thank you in ...

Explain to me the process of passing functions in TypeScript

class Testing { number = 0; t3: T3; constructor() { this.t3 = new T3(this.output); } output() { console.log(this.number); } } class T3 { constructor(private output: any) { } printOutput() { ...

Update the header background color of an AG-Grid when the grid is ready using TypeScript

Currently working with Angular 6. I have integrated ag-grid into a component and I am looking to modify the background color of the grid header using component CSS or through gridready columnapi/rowapi. I want to avoid inheriting and creating a custom He ...