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
According to console logs, ngAfterViewInit is called before data are loaded. how can I correct this?.

Access-Control-Allow-Originheader in the request as it is a response header. It belongs on the API server.ngOnInittongAfterViewInit. and movedataSource = ...intonextcallback.this.dataSource.paginator = this.paginator;this.dataSource.sort = this.sort;inside your subscribe function -after thethis.dataSource = new MatTableDataSource(..). Yes, you can remove the ngAfterViewInit function.