Search code examples
angularangular6angular-services

Property 'data' does not exist on type 'Object'


i get this error on my angular 6 project when i try to fetch data from my api. This is my api json file;

{"data":
[{"category_name":"Women Ready Made","slug":null,"image_url":"education.jpg","products": 
[{"productName":"Kampala 
Shorts","description":"Beautiful Handwoven Kampala Shorts","imageUrl":"C:\\codes\\Tradsonline\\img\\image1.jpg","price":2500,"discount":10},{"productName":"Flowing White Agbada","description":"Flowing white agbada with beautiful design.","imageUrl":"C:\\codes\\Tradsonline\\img\\image3.jpg","price":22000,"discount":15}]},{"category_name":"Men's Ready Made","slug":null,"image_url":"education.jpg","products":[{"productName":"Ankara Jacket","description":"Ankara Jackets with pockets.","imageUrl":"C:\\codes\\Tradsonline\\img\\image2.jpg","price":5000,"discount":15},{"productName":"Women Ankara Gown","description":"Women Ankara gown with beautiful design.","imageUrl":"C:\\codes\\Tradsonline\\img\\image4.jpg","price":8000,"discount":0}]},{"category_name":"Ankara Gowns","slug":null,"image_url":"education.jpg","products":[]}]}

This is my service

getCategories(): Observable<Category[]> {
  return this.http.get(this.base_url + 'categories')
    .pipe(map(res => {
       return res.data; //this is where the error happens
}));

this are my imports on my service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Product } from '../models/product';
import { Category } from '../models/category';

import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

Where does the error come from?


Solution

  • If you do not specify a generic type parameter for http.get call then object is assumed so that is the type passed into map. object does not have a property named data (that you are calling) hence the transpile time error.

    Change it so that you define the returned structure in the generic type constraint in the call to http.get<T>.

    getCategories(): Observable<Category[]> {
        return this.http.get<{data: Category[]}>(this.base_url + 'categories')
            .pipe(map(res => {
              return res.data; // now .data is known and is expected to contain Category[]
            }));
    }