Page Breaks - Patience in anticipation of dataSource readiness

I am facing an issue with my pagination service and component. The dataSource appears empty when the page is loaded for the first time, but by the second time it is populated and I can display the dataTable and paginate successfully.

Is there a workaround to ensure that the function is invoked only after the data has been fully loaded?

setTimeOut() does not seem to be a viable solution based on my previous attempts.

list-user.service.ts:

let registeredUser:Users[] = [];
@Injectable()
export class ListUserService {
    constructor(public loginService:LoginService){}
    getUserDatasource(page:number, limit:number, sortBy?:string, sortType?:DatatableSortType): IPaginableUsers {

      this.loginService.getUsersList().subscribe(
        (res) => {
          registeredUser = res.message
            return registeredUser; 
        }, (err) => {})
    }
    ...
    ...
}

list-users.component.ts:

export class ListUsersComponent implements AfterViewInit, OnDestroy {

    ...
    ...
    constructor( private listUserService:ListUserService, private changeDetectorRef:ChangeDetectorRef) {
            this.fetchUserDataSource();
    }
       ngOnInit(){}

    ngAfterViewInit() {
        if (this.datatable) {
            Observable.from(this.datatable.selectionChange).takeUntil(this.unmount$).subscribe((e:IDatatableSelectionEvent) =>
                this.currentSelection$.next(e.selectedValues)
            );

            Observable.from(this.datatable.sortChange).takeUntil(this.unmount$).subscribe((e:IDatatableSortEvent) =>
                this.fetchUserDataSource(this.currentPagination.currentPage, this.currentPagination.itemsPerPage, e.sortBy, e.sortType)
            );

            Observable.from(this.pagination.paginationChange).takeUntil(this.unmount$).subscribe((e:IDatatablePaginationEvent) =>
                this.fetchUserDataSource(e.page, e.itemsPerPage)
            );
        }
    }

    ngOnDestroy() {
        this.unmount$.next();
        this.unmount$.complete();
    }

    shuffleData() {
        this.users$.next(shuffle(this.users$.getValue()));
        this.currentSelection$.next([]);
        this.changeDetectorRef.detectChanges();
    }
       private fetchUserDataSource(page:number = this.currentPagination.currentPage, limit:number = this.currentPagination.itemsPerPage, sortBy:string | undefined = this.currentSortBy, sortType:DatatableSortType = this.currentSortType) {
        if (sortBy) {
          this.currentSortBy = sortBy;
          this.currentSortType = sortType;
        }

        const { users, pagination } = this.listUserService.getUserDatasource( page, limit, sortBy, sortType);

        this.users$.next(users);
        this.currentSelection$.next([]);
        this.currentPagination = pagination;
    }
}

Answer №1

Make sure to subscribe during the ngOnInit lifecycle hook to this.listUserService.getUserDataSource within your list-user-component

export class ListUsersComponent implements OnInit,...
{
   page:number=1;
   limit:number=5;
   sortBy:string='';
   ....
   ngOnInit() {
     this.listUserService.getUserDataSource(page, limit, sortBy, sortType).subscribe((res)=>{
         ....add your logic here ...
     }
  }

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

What are the steps to conduct a vulnerability scan on an Angular/Node application?

I'm in the process of setting up a vulnerability check for my Angular 7/Node project. Can anyone advise on how to effectively run this type of process? Are there any recommended tools available? Initially, I attempted to use the dependency-check-mave ...

In TypeScript Next.js 14 APP, object literals are limited to declaring existing properties

I encountered an error in my typescript next.js 14 APP. I need assistance resolving this issue, which states: Object literal may only specify known properties, and 'productPackages' does not exist in type '(Without<ProductCreateInput, Pr ...

Endlessly triggering a function with React Context

I am facing an issue with the profile loading function in my context. It seems to be executing repeatedly instead of only once or when necessary. For instance, I have two modals - one for cases where no profile exists and another for cases where a profil ...

Scala interprets JSON data in a condition

I am currently working with two classes that have a common parent in Scala. My goal is to implement a shared JSON reader within the parent class that can determine and return the appropriate child class based on the supplied JSON data. To better illustrate ...

Troubleshooting a Gulp.js issue during the execution of a "compile" task

Currently, I am utilizing gulp to streamline a typescript build system specifically designed for an Angular 2 frontend. However, I have encountered a problem with my "build" task that has been configured. Below is the exact task in question: gulp.task(&a ...

TypeScript: Despite declaring specific types, generic functions still treat parameters as "any"

When using TypeScript 4.4.3, I am looking to specify the types of function parameters for a function that returns a generic. However, TypeScript seems to be treating the parameters as any when working with functions that involve generics. Here's a si ...

What is the best way to extract data from a proxy in VUE3?

Currently, I am utilizing the ref() function to store data retrieved from Firebase. However, when attempting to filter and retrieve a single record, the outcome is not as expected. Instead of returning a single object, something different is being displaye ...

Change the URL structure from ex.com/forum?id=1 to ex.com/#/forum?id=1 in AngularJS

Hey there! I'm in the process of creating a Forum using AngularJS and need some guidance. First things first! I've successfully established a connection to my database with: <?php session_start(); $db = new mysqli("localhost","root",""," ...

Tips for extracting JSON data from test.properties file in the presence of other web elements

I have a set of WebElements stored in a test.properties file and I am struggling to read and extract all the JSON data from it. Can someone assist me in extracting all the JSON data from a properties file using Java? I have attempted various methods to re ...

A step-by-step guide on decoding JSON data received from the tweepy API

After researching how to scrape tweets using tweepy, I came across a solution based on the first answer of this question. The code provided is as follows: consumer_key = "" consumer_secret = "" access_token = "" access_token_secret = "" import tweepy au ...

Running an HTTP request conditionally within combineLatest

I'm working on a combineLatest function that makes 2 http requests, but I only want the second request to be made if a specific condition is satisfied. combineLatest([ this.leadsService.fetchALLLeadsActivityChart(this.clientId, this.getParams(option ...

Is there a way to store a detailed dictionary in a JSON file, and then retrieve it as a dictionary?

I'm a bit confused about using the json library in Python. I save a nested dictionary to a json file on disk and then try to load it back as it was originally. However, when I load the file, the object is not the same as before. mydictionary=default ...

JSON is not conforming to the standard nesting level

After simplifying, the JSON implementation is as follows: Data(Entity)->"data"->another Entity I originally thought I could decrypt the Data object first, extract a type from it, and then use that type to decrypt the necessary type from the String ...

Error: An unhandled exception occurred during component destruction: TypeError: Cannot access property 'unsubscribe' of undefined

I encountered an issue while trying to unsubscribe during the ngOnDestroy method in my shopping-edit.component.ts file, specifically when clicking on the link to navigate to my recipes page. Here is a screenshot demonstrating the error: error on link clic ...

Tips for removing a specific dynamic element in HTML using an Angular reactive form

I successfully implemented a dynamic reactive form that allows users to add or delete fields dynamically. However, I am facing an issue with removing the Radio Button (And / Or) from the last row. I would like it to only appear for the first and second row ...

Attribute specified does not belong to type 'DetailedHTMLProps<ButtonHTMLAttributes

I am working on creating a reusable 'button' component and I would like to include a href attribute so that when the button is clicked, it navigates to another page. An Issue Occurred: The following error was encountered: 'The type '{ ...

The ordering of my styles and Material-UI styles is causing conflicts and overrides

Greetings fellow developers! I'm currently facing an issue with my custom styles created using makeStyles(...). The problem arises when I import my styles constant from another module, and the order of the style block is causing my styles to be overr ...

Remove observableB if it is triggered 1 second after observableA

Imagine having two different observables, known as observableA and observableB. There are 3 possible scenarios for how these observables can be activated: only observableA is activated. only observableB is activated. observableA is activated first, follo ...

Is it possible for TypeScript to automatically determine the specific type that was used in a union type parameter?

I need some help with a utility function I'm working on that can remove a specified number of elements from either a string or an array. My goal is to have the compiler determine whether the return value should be a string or an array based on what is ...

Checking if the Cursor is Currently Positioned on a Chart Element in Word Addin/OfficeJS

I am looking for a way to determine if the document cursor is currently positioned inside of a Chart element using the Microsoft Word API. My current application can successfully insert text, but when I attempt to insert text into the Chart title, it ends ...