Adalat  Khan

Adalat Khan

  • 1k
  • 1.5k
  • 750.4k

Map backend data to interface

Jul 27 2022 9:59 PM

Hi,

I am new in Angular. i have issue in mapping. I called Web API in Angular following is the Json object coming from the backend:

{
  "productCategoryDataModel": [
    {
      "productsCategortyName": "Electronics",
      "productsList": [
        {
          "id": 1,
          "productName": "Laptop",
          "productDescription": "Laptop Core i7",
          "productImageUrl": "fsdgdfgdfgdfgd"
        },
        {
          "id": 5,
          "productName": "IPad",
          "productDescription": "IPad",
          "productImageUrl": "hgfhgfhgf"
        }
      ]
    },
    {
      "productsCategortyName": "Grocery",
      "productsList": [
        {
          "id": 3,
          "productName": "Tomato",
          "productDescription": "Tomato",
          "productImageUrl": "dgdfgdfggdfgdf"
        },
        {
          "id": 4,
          "productName": "Onion",
          "productDescription": "Onion",
          "productImageUrl": "hgfhgfgh"
        }
      ]
    }
  ]
}

I have created the following interface in angular for this json:

export interface IProductsResponse {
  ProductCategoryDataModel: ProductCategoryDataModel[];
}
export interface ProductCategoryDataModel
{
ProductsCategortyName: string
productsList: ProductsList[];
}
export interface ProductsList
{
ProductId: number;
ProductName: string;
ProductDescription: string;
ProductImageUrl: string;
}

Following is my Service class that calling the API:

@Injectable({
  providedIn: 'root'
})
export class ProductsListService {
  apiUrl: string = 'https://localhost:7025/api/ProductsManagement/GetAllProducts';
  constructor(private httpClient: HttpClient) { }
  getProductsGalleryData(): Observable<IProductsResponse[]> {
    return this.httpClient.get<IProductsResponse[]>(this.apiUrl);
  }

Following is my component ts file:

@Component({
  selector: 'app-products-gallery',
  templateUrl: './products-gallery.component.html',
  styleUrls: ['./products-gallery.component.css']
})
export class ProductsGalleryComponent implements OnInit {
  productsList: IProductsResponse[] | undefined;
  constructor(private _galleryProducts: ProductsListService) { }
  ngOnInit(): void {
    this._galleryProducts.getProductsGalleryData().subscribe(data => {
    this.productsList = data;
    console.log(data);
    });
  }
}

The data is displayed in the Console in the form of json but i have issue in the HTML file because when i use the ngFor loop for ProductsList it gimes me error so how to map the response into the interface and how to write the html to display this data?


Answers (1)