The onInit Observable subscription will only execute a single time

Within my table, I have a list of names and an input tag that filters the content of the table when its value changes. The data is retrieved from an HTTP request to a service.

I am encountering three different scenarios:

1- If I subscribe to this.ds.getDrogas() only in the ngOnInit() function, the table displays all the content but the filter does not work. 2- If I subscribe to this.ds.getDrogas() only in the filterName() function, the table initially appears empty. However, once I change the input value, the filter starts to work correctly. If I delete the input's content, the table shows all the data again, and if I write something new, the filter functions properly. 3- If I subscribe to the observable in both functions, it behaves as expected. The table initially displays all the content, and the filter works correctly when the input value changes.

I am aware that the code within ngOnInit() is only executed once, but should a subscription continue listening for observable changes?

I would greatly appreciate your assistance.

Service Side:

getDrogas(): Observable <HttpResponses> {
    return this.http.get<HttpResponses>(this.apiUrl +'/drogas')
  }

Table-Component.ts:

    ngOnInit{
        this.ds.getDrogas().pipe(
        map((data)=> data.data
        .filter(element=> element.identificacion.nombre.startsWith(this.contador))))
        .subscribe(res=> {this.dataDroga= res; console.log('Ejecutado con valor de contador'+ 
        this.contador)});
    }

   contador: string =''

   filterName(){
   this.ds.getDrogas()
   console.log(this.dataDroga)
   }

Table-Component.html:

<input  type="text" [(ngModel)]='contador' (ngModelChange)='filterName()'>

Answer №1

this.ds.getDrogas() method returns an Observable in Angular, requiring a subscription to fetch data from the server. Subscribing in the ngOnInit() ensures that you receive the initial data.

To optimize API calls and prevent excessive requests, consider leveraging the debounceTime operator within the ngModelChange handler. Implementing this solution will enhance performance by delaying unnecessary API queries.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  filterValue$ = new BehaviorSubject('');
  filterValue = '';

  constructor(private api: ApiService) {}

  ngOnInit(): void {
    this.filterValue$.pipe(
      debounceTime(DEBOUNCE_TIME),
      switchMap(filterValue => this.api.getData().pipe(
        map(dataFromServer => filterData(dataFromServer, filterValue)),
      )),
      /* Remember to UNSUBSCRIBE correctly upon component destruction */
      tap(filteredData => {
        console.log(filteredData);
        /* Include update table logic here */
      }),
    ).subscribe();
  }

  onFilterChanged(value: string): void {
    console.log(value);
    this.filterValue$.next(value);
  }
}

function filterData(dataFromServer: any, filterValue): any {
  // ADD YOUR LOGIC HERE
  return dataFromServer;
}

Access the full code snippet at https://stackblitz.com/edit/angular-txwgmk

P.S.

Remember to unsubscribe from observables in your component to avoid memory leaks.

Hope this explanation proves beneficial!

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

Ways to retrieve a value from outside the Angular subscribe block

Custom Template <div class="row" *ngFor="let otc of this.jsonData;index as j"> <div> <table class="table table-striped table-fixed"> <tr *ngFor="let opc of this.winServiceInfo ...

Retrieve the values of private variables within a defined function

While experimenting with typescript, I have encountered an issue that I can't seem to resolve. My project involves using Angular, so I will present my problem within that context. Here is a snippet of my code: class PersonCtrl{ private $scope: I ...

Ways to incorporate NPM packages into your browser projects using TypeScript

This is the current setup: index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <script src="../node_modules/systemjs/dist/system.js"></script> <script src="../node_modules/lodash/in ...

Customizing date colors in JavaScript: A step-by-step guide

var active_dates1 = ["2017-04-02 00:00:00","2014-04-03 00:00:00","2014-04-01 00:00:00"]; $('.datePick', this.$el).datepicker( beforeShowDay: function (date) { for(let date1 of active_dates1){ if (date.getTime( ...

How does NgRx handle updating remote data once it has been modified?

I'm struggling to grasp the inner workings of NgRx. My user list is retrieved from a Firebase store using a service like this: getAllUsers():Observable<object>{ console.log('getAllUsers'); return this.afs.collection('us ...

What is the TypeScript syntax for defining a component that does not require props to be passed when called?

Can you provide guidance on the correct type to specify for Component in order to compile this example without any type errors? import { memo } from "react"; import * as React from "react"; export function CustomComponent( props: ...

Unable to apply the CSS styles on the webpage

I'm having trouble adjusting the CSS for a specific div with the class .cropper inside a component named image-cropper, and I can't figure out why it's not taking effect. Here is an image of the particular div. https://i.sstatic.net/spdJc. ...

What is the process for incorporating the 'url-regex' npm package into an Angular(2/4) project?

I'm currently working on a project with Angular 4 and I've run into some issues while trying to use the url-regex package within my Component. After some troubleshooting, I discovered that this approach seems to work: import * as urlRegex from ...

Enhance your webpage design with stylish CSS formatting using Bulma cards

My HTML output is as follows: https://i.stack.imgur.com/aBdEF.jpg It seems that the footer is not matching up with the cards... The CSS component I am using looks like this: .card-equal-height { display: flex; flex-direction: column; height: 100%; ...

Adding properties to React Component

Due to security reasons, I am required to update the ant design library in my codebase from version 3 to 4. In the past, this was how I used the icon: import { Icon } from 'antd'; const Demo = () => ( <div> <Icon type="smile" ...

Having trouble importing PouchDB into an Angular 5.2.0 project

Struggling with integrating PouchDB into my Angular project, I've experimented with various import methods : import PouchDB from 'pouchdb'; import * as PouchDB from 'pouchdb'; In my service, I'm utilizing it like this : dat ...

Angular 11 along with RxJS does not support the combineLatest method in the specified type

Hey there, I'm currently working on utilizing the combineLatest operator to merge two streams in Angular, but I keep encountering an error message stating that "combineLatest does not exist on type". I've attempted to move the code into a .pipe() ...

Angular Service Worker enhancements across various domains

Scenario Our team is currently developing an Angular application that is accessible through multiple domains. Depending on the domain, the app will display different colors and content, but it is essentially the same Angular application. To enhance perfo ...

How to Insert a New User into the Database Using Angularfire2

During the login process, I implemented the following method: login() { this.auth.login(); this.authService.login().subscribe(() => { if (this.authService.isLoggedIn) { console.log("ADDING THE USER.."); // Insert a new user into the use ...

How to implement the ECharts animated bar chart in Angular version 16?

The animated bar chart in ECharts functions perfectly on Stackblitz. You can check it out here in the Stackblitz Angular 16 demo. However, attempting to run the same demo in a local Angular 16 project led to the following errors. Error: src/app/animated- ...

Learn the steps to refresh a component in Angular 5

src/shared.service.ts public _testData:any;   set testData(value:any) {     this._testData = value   }   get testData():any {     return this._testData;   } src/header.component.ts private postValues( ...

The MaterialTable component is indicating that there is no property called 'tableData' on the IPerson type

Incorporated an editable attribute to my MaterialTable component. Currently looking for a way to retrieve the index of updated or deleted items within the onRowUpdate and onRowDelete methods. To replicate the issue, refer to this minimal sandbox example: ...

Angular Version 11 is throwing a NullInjectorError with the message: "No provider found for Control

I recently implemented a custom input component based on the guidance provided in this interesting article: medium.com: dont-reinvent-the-wheel. Below is the code snippet I used, written in strict mode ▼ // input.component.ts import { Component, Input, ...

Can a reducer be molded in ngrx without utilizing the createReducer function?

While analyzing an existing codebase, I came across a reducer function called reviewReducer that was created without using the syntax of the createReducer function. The reviewReducer function in the code snippet below behaves like a typical reducer - it t ...

Comparing Angular 2's location.go with window.location.href

It is clear to me that location.go will alter the URL in the browser without refreshing the page, while window.location.href will reload the entire page. However, what I am uncertain about is how these methods impact SEO. The structure of my site's U ...