0

I have a issue with sorting and pagination of a angular material table. Source code is as given below.

 ngOnInit(): void {
    console.log("ngOnInit started");
    this.shoppingcartService.GetShoppingCart().subscribe({
      next: (data: ShoppingCart) => {
        this.shoppingCart = data;
        console.log("data loaded");
        this.shoppingCart.shoppingCartItems.forEach((item) => {
          item.productName = item.product?.name;
        });
        this.dataSource = new MatTableDataSource(this.shoppingCart.shoppingCartItems);       
      },
      error: (error: any) => {
      },
      complete: () => {  
      }
    });
    console.log("ngOnInit ended");
  }

  ngAfterViewInit() { 
    console.log("ngAfterViewInit started");
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort; 
    console.log("ngAfterViewInit end");
  }

code of the "GetShoppingCart" method is this

  GetShoppingCart() : Observable<IShoppingCart> {
    let url = global.serverBase + "/api/ShoppingCarts/GetShoppingCartAsync";
    let headers = new HttpHeaders()
    .set('content-type','application/json')  
    .set('mode','no-cors')
    .set('Access-Control-Allow-Origin','*');
    return this.httpClient.get<IShoppingCart>(url,{'headers':headers}).pipe(
      map((data:IShoppingCart)=>{ 
        return data;
      }),
      catchError((error,caught)=>{
        throw error;
      })
    )
  } 

backend Api method

[HttpGet]
[Route("GetShoppingCartAsync")]
public async Task<ActionResult> GetShoppingCartAsync()
{
   //code................ 
}

console logs are in the above "ngOnInit" and "ngAfterViewInit" methods are printed in this order

enter image description here

According to console logs, ngAfterViewInit is called before data are loaded. how can I correct this?.

3
  • Why does it matter? The data will come when the server responds and the data are constructed and available, not before. Also, you don't need to/shouldn't send the Access-Control-Allow-Origin header in the request as it is a response header. It belongs on the API server. Commented Jun 25, 2024 at 17:51
  • try to move all code from ngOnInit to ngAfterViewInit. and move dataSource = ... into next callback. Commented Jun 25, 2024 at 20:43
  • 1
    Always you create a new dataSource, you should indicate again the sort and paginator properties. So, just add the this.dataSource.paginator = this.paginator;this.dataSource.sort = this.sort; inside your subscribe function -after the this.dataSource = new MatTableDataSource(..). Yes, you can remove the ngAfterViewInit function. Commented Jun 26, 2024 at 6:58

1 Answer 1

0

I fixed the issue by changing the code. The paginator and the sort bound like this.

  paginator: MatPaginator= new MatPaginator(new MatPaginatorIntl(), ChangeDetectorRef.prototype);
  sort: MatSort= new MatSort();
  @ViewChild(MatPaginator, { static: true }) set matPaginator(mp: MatPaginator) {
    this.paginator = mp;
    this.dataSource.paginator = this.paginator;
  }
  @ViewChild(MatSort) set matSort(ms: MatSort) {
    this.sort = ms;
    this.dataSource.sort = this.sort;
  }

I removed ngAfterViewInit() method and used the ngOnInit() method to assign the paginator and the sort properties in complete section.

  ngOnInit(): void { 
    this.shoppingcartService.GetShoppingCart().subscribe({
      next: (data: ShoppingCart) => {
        this.shoppingCart = data; 
        this.shoppingCart.shoppingCartItems.forEach((item) => {
          item.productName = item.product?.name;
        });
        this.dataSource = new MatTableDataSource(this.shoppingCart.shoppingCartItems);
      },
      error: (error: any) => { },
      complete: () => {   
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;  
      }
    }); 
  } 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.