Error with same type in an object and behaviour subject

Discussão em 'Angular' iniciado por Aviral Vikram, Fevereiro 26, 2025.

  1. All I did was replace the type in artworks from any[] to ArtList (class) and updated the methods for that, but now TypeScript is showing me this error without much clue as where the type are different from or how they are unrelated.

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs';
    import { ExploreApiService } from '../../exploreApiService/explore-api.service';
    import { Art, ArtAdaptor, ArtList, ArtListAdaptor } from '../../../../../models/classes/art.model';

    interface CategoryData {
    artworks: any[];
    currentPage: number;
    totalPages: number;
    isLoading: boolean;
    }

    @Injectable({
    providedIn: 'root',
    })
    export class CategoryStateService {
    private categoriesSubject = new BehaviorSubject<{ [key: string]: CategoryData }>(
    {
    // "": { artworks:new ArtList(),
    // currentPage:0,
    // totalPages:0,
    // isLoading:false
    // }
    }
    );


    categories$ = this.categoriesSubject.asObservable();

    initializeCategories(categoryList: string[], apiService: ExploreApiService, predefinedCategories: string[] = []) {
    // Initialize the categories state
    const initialState: { [key: string]: CategoryData } = {};

    // Initialize from the categoryList API response
    categoryList.forEach((category) => {
    initialState[category] = {
    artworks: [],
    // artworks: new ArtList(),
    currentPage: 0,
    totalPages: 0,
    isLoading: false,
    };
    });

    // Add predefined categories like 'Top Arts'
    predefinedCategories.forEach((category) => {
    initialState[category] = {
    artworks: [],
    // artworks: new ArtList(),
    currentPage: 0,
    totalPages: 0,
    isLoading: false,
    };
    });

    // Now update the BehaviorSubject with the initial state
    this.categoriesSubject.next(initialState);

    // Load data for all categories, including predefined ones like 'Top Arts'
    [...categoryList, ...predefinedCategories].forEach((category) => {
    this.loadMoreData(category, apiService);
    });
    }

    loadMoreData(category: string, apiService: ExploreApiService) {
    const categories = this.categoriesSubject.value;
    const categoryData = categories[category];

    if (!categoryData) {
    console.error(`Category ${category} does not exist in the state.`);
    return;
    }

    if (categoryData.isLoading || (categoryData.totalPages && categoryData.currentPage >= categoryData.totalPages)) {
    return;
    }

    categoryData.isLoading = true;

    // If the category is 'Top Arts', fetch it from the API
    if (category === 'Top Arts') {
    apiService.getTopArtOfTheWeek().subscribe({
    next: (res: any) => {
    // categoryData.artworks = ArtListAdaptor.adapt(res.data.content);
    categoryData.artworks = [...res.data.content];
    categoryData.totalPages = res.data.totalPages;; // Top Arts is a single page
    categoryData.currentPage += 1;
    categoryData.isLoading = false;
    this.categoriesSubject.next(categories); // Trigger update after data is loaded
    },
    error: () => {
    categoryData.isLoading = false;
    },
    });
    } else {
    // Call the API for other categories
    apiService.getArtByCategory(category, categoryData.currentPage, 10).subscribe({
    next: (res: any) => {
    if(res.data && res.data.content){

    const arts:Art[] = res.data.content.map((el:any) => ArtAdaptor.adapt(el));

    // categoryData.artworks.addArt(...arts);
    categoryData.artworks.push(...arts);
    categoryData.totalPages = res.data.totalPages;
    categoryData.currentPage += 1;
    categoryData.isLoading = false;
    this.categoriesSubject.next(categories); // Trigger update after data is loaded
    }
    },
    error: () => {
    categoryData.isLoading = false;
    },
    });
    }
    }

    // Add this method to trigger category update
    triggerCategoryUpdate(category: string) {
    const categories = { ...this.categoriesSubject.value };
    if (categories[category]) {
    this.categoriesSubject.next({ ...categories });
    }
    }

    updateArtworkLikeState(artworkId: any, liked: boolean) {
    const updatedCategories = { ...this.categoriesSubject.value }; // Clone the categories object
    console.log(this.categoriesSubject.value,"BHALUE");

    Object.keys(updatedCategories).forEach((categoryKey) => {
    const category = updatedCategories[categoryKey];
    const updatedArtwork:Art[] = category.artworks.arts.map((artwork:Art) => {
    if (artwork.id === artworkId) {
    return artwork.setLike(liked); // Return a new object for the updated artwork
    }
    return artwork;
    });

    // Update the category with a new reference
    updatedCategories[categoryKey] = {
    ...category,
    artworks: new ArtList(updatedArtwork),
    };
    // updatedCategories[categoryKey].artworks.updateArts(updatedArtwork)

    // updatedCategories.art
    });

    // Emit the updated state
    this.categoriesSubject.next(updatedCategories);
    }

    }



    The error I am getting:

    ✘ [ERROR] TS2719: Type 'import("/home/aviral/digital-arts-frontend/node_modules/rxjs/dist/types/internal/Observable").Observable<{ [key: string]: CategoryData; }>' is not assignable to type 'import("/home/aviral/digital-arts-frontend/node_modules/rxjs/dist/types/internal/Observable").Observable<{ [key: string]: CategoryData; }>'. Two different types with this name exist, but they are unrelated.
    Type '{ [key: string]: CategoryData; }' is not assignable to type '{ [key: string]: CategoryData; }'. Two different types with this name exist, but they are unrelated.
    'string' index signatures are incompatible.
    Type 'CategoryData' is not assignable to type 'CategoryData'. Two different types with this name exist, but they are unrelated.
    Types of property 'artworks' are incompatible.
    Type 'ArtList' is missing the following properties from type 'Art[]': length, pop, push, concat, and 29 more. [plugin angular-compiler]


    Why is TypeScript saying that the type in behaviour subject is different from my object?

    Continue reading...

Compartilhe esta Página