Reorganizing Execution Order in AfterViewInit with Subscriptions in Angular 10

In my component, I am using the ngAfterViewInit lifecycle hook to handle certain tasks:

ngAfterViewInit() {
    this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);

    this.subscription = this.dataService.dataChanged
      .subscribe(
        () => {
          this.getData();
        }
      );

    this.getData();
  }

I am facing an issue where I want the subscription logic to run before the this.getData() outside the subscription block. If for some reason the subscription does not run, then I would like the this.getData() outside the subscription to execute.

The challenge is that placing this logic in ngOnInit does not work as expected due to the paginated nature of the table. The subscription needs to be triggered when new data is added to the table so that it can be displayed automatically to the user.

Updated Scenario: Currently, when a user navigates to the page, the initial data is loaded onto the paginated table correctly. Subsequently, if the user adds a new item via a form on another element and returns to the table view, the previous behavior loads the table initially without the newly added item, requiring a reload to display all data including the addition. Ideally, I would prefer that upon navigating back, the updated data is instantly visible to the user without the need for a manual refresh.

Answer №1

To improve the performance of your code, consider adjusting the flow to account for asynchronous subscriptions.

 private callGetData: boolean

 ngAfterViewInit() {

    this.callGetData = true;

    this.sort.sortChange.subscribe(() => {
       this.paginator.pageIndex = 0;
       if(this.callGetData) this.getData();
       this.callGetData = false;
    })

    this.subscription = this.dataService.dataChanged
      .subscribe(
        () => {
          this.getData();
        }
      );
  }

This setup ensures that getData() is only called after ngAfterViewInit() is completed, not every time an event is received by the subscription.

If preferred, you can remove the flag and include getData() directly within the subscription as well.

Hopefully, this adjustment resolves any issues!

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

Are you harnessing the power of Ant Design's carousel next and previous pane methods with Typescript?

Currently, I have integrated Ant Design into my application as the design framework. One of the components it offers is the Carousel, which provides two methods for switching panes within the carousel. If you are interested in utilizing this feature using ...

Working with nested arrays in TypeScript and how to push values onto them

I am facing some challenges with nested array behavior in TypeScript. I am looking for a way to define a single type that can handle arrays of unknown depth. Let me illustrate my issue: type PossiblyNested = Array<number> | Array<Array<number& ...

The letter 'X' is not suitable for use as a JSX component because its return type 'Element[]' does not qualify as a valid JSX element

Currently, I am working on rendering two simple joke cards in TypeScript. The cards are displaying correctly in my browser, but I've encountered an error message that says: 'Jokes' cannot be used as a JSX component. Its return type 'Ele ...

Error in Typescript syntax within a CommonJS/Node module: Unexpected colon token found in function parameter

After validating the file with TS, there are no more errors. However, during runtime, I encounter an "Unexpected token ':'" error on any of the specified TS, such as immediately erroring on function (err: string). The following are my build and ...

Turn off or delete certain features within an npm package

Is it possible to disable or remove unused functions in a npm library? I only need certain functions from the library and don't want others to be accessible. I want to retain the read function while disabling the write function to prevent developers ...

Encountering an issue while attempting to make an in-app purchase with Ionic 3 and Cordova - receiving the error message "Sorry, the item you are trying to

In the process of developing my app with IONIC 3 and Angular 4, I have integrated the following Ionic plugin for in-app purchases: https://ionicframework.com/docs/native/in-app-purchase/ Once the plugin was installed, I included the "play_store_key" in t ...

Is there a way to change an ISO 8601 date into the format '/Date(1525687010053)/' using JavaScript?

Is there a way to convert a date value that is formatted as 9999-12-31T00:00:00Z to the format /Date(1525687010053)/ using javascript? I tried implementing the following code, but it doesn't seem to be working: var datevalue = '9999-12-31T00:00 ...

A guide to effectively unit testing StripeJs within the Karma testing framework for Angular 8

I'm currently facing a challenge in unit testing a payment component that relies on StripeJS. In my 'ng-app.js' file, I import it as follows: stripe: /*@ngInject*/ function ($ocLazyLoad) { return $ocLazyLoad.load({ ...

I am curious if there is a feature in intro.js that allows for the highlighting of text or images to

I am having trouble getting intro.js to work with Ionic 4 as the highlighted text is not showing up view image here This is how I implemented the code in Angular 7: intro() { let intro = introJs.introJs(); intro.setOptions({ exitOnOverlayClick: false, ...

Managing Geolocation in Ionic2 presenting challenges

Attempting to utilize Geolocation in ionic2 for device location access. Referred to the official documentation on https://ionicframework.com/docs/native/geolocation/. Successfully installed the necessary packages: $ ionic plugin add cordova-plugin-geoloca ...

Can a specific type be created for a nested object that has varying levels of depth?

One of my functions organizes objects based on the length of an input array. For example: fn(['a']) -> Record<string, string> fn(['a', 'b']) -> Record<Record<string, string>> I've defined the ret ...

Bringing TypeScript modules from a local module into a React application

As I work on organizing my projects and keeping logic separate in components that will eventually be published, I have a specific structure set up for now: I have a library of Typescript scripts within a project named project-a A separate React app create ...

Enhance your React Typescript High Order Component by incorporating additional properties and implementing them

I am in the process of creating a React HOC with specific requirements: It should take a component as input, modify the hidden property (or add it if necessary), and then return the updated component The rendered component should not display anything whe ...

What could be causing my date variable to reset unexpectedly within my map function?

Currently, I'm utilizing a tutorial to create a custom JavaScript calendar and integrating it into a React project You can find the functional JavaScript version in this jsfiddle import { useState, useRef, useMemo } from 'react' import type ...

What is the process for running an npm package command on a specific subdirectory using PowerShell?

Is there a way to run an npm package command on a specific subdirectory using PowerShell? My situation involves having an ng2 application embedded within a .NET MVC app. The ng2 directory is nested within the main root directory structured as MySite/ng2. ...

Bidirectional data binding in Autocomplete component's matInput

Utilizing a material autocomplete input to search for an article in a database, I originally had a standard input in a table column with the ngModel directive for two-way databinding. To switch this input to an autocomplete input, I followed Angular's ...

Having trouble retrieving certain header values in Angular 4

Using Angular 4, I am making a back-end query like this: this.classzService.query({ page: this.page, size: this.itemsPerPage, sort: this.sort(), url: url }).subscribe( (res: Response) => this.onQuerySuccess(res.jso ...

What is the process for adjusting the color of a mat-divider?

Has anyone been successful in changing the color of mat-divider? I attempted the following but had no luck: component.html <mat-divider class="material-devider"></mat-divider> component.scss .material-devider { color: red } ...

Execute the form validation and submission simultaneously

I am facing an issue with my form validation and submission process. When I click on the creer button, the form validation works fine but the submit function does not work. I don't see any errors in my console. I have tried using the onsubmit() method ...

Angular Express Route Guide

I've encountered an issue with my express angular app. When I am on a specific URL like http://localhost:4007/login and refresh the page, I keep getting an error. I've tried multiple solutions to fix it, but nothing seems to work. Here is a snip ...