fix: author prefetch did not work (moved away from excessive effect() usage, implemented additional methods to avoid missmatches)
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
Kazgatari
2026-08-06 16:30:28 +02:00
parent c70a566514
commit daa4f79ea0
4 changed files with 358 additions and 278 deletions
@@ -1,4 +1,6 @@
import { Injectable, inject, signal } from '@angular/core';
import { Subject, of } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
import {
UniversityRankingsService,
PersonsService,
@@ -42,6 +44,124 @@ export class TrendDataService {
private readonly cacheMap = new Map<string, TrendResponse>();
// RxJS Subjects for cancellation of pending requests
private readonly topTopicsSubject = new Subject<{
cleanId: string;
entityType: string;
startYear: number;
endYear: number;
searchType: string;
}>();
private readonly instSuggestionsSubject = new Subject<{
topic: string;
countryFilter?: string;
regionFilter?: string;
}>();
private readonly recAuthorsSubject = new Subject<{
topic: string;
primaryInstId: string;
}>();
constructor() {
this.topTopicsSubject
.pipe(
switchMap((params) => {
if (!params.cleanId || params.searchType === 'all') {
this.isTopTopicsLoading.set(false);
this.topTopicsData.set([]);
return of([]);
}
return this.apiService
.getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet(
params.cleanId,
params.entityType,
params.startYear,
params.endYear,
params.searchType,
)
.pipe(
map((res) =>
(res.items || []).map((item) => ({
value: item.count,
name: item.name,
})),
),
catchError((err) => {
console.error('Failed to load top topics:', err);
this.topTopicsError.set(true);
return of([]);
}),
);
}),
)
.subscribe((data) => {
this.topTopicsData.set(data);
this.isTopTopicsLoading.set(false);
});
this.instSuggestionsSubject
.pipe(
switchMap((params) =>
this.apiService
.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(
params.topic,
params.regionFilter,
params.countryFilter,
6,
)
.pipe(catchError(() => of([]))),
),
)
.subscribe((data: any) => {
this.topSuggestions.set(data || []);
this.isSuggestionsLoading.set(false);
});
this.recAuthorsSubject
.pipe(
switchMap((params) => {
const cleanInst = cleanEntityId(params.primaryInstId) || 'I62318514';
return this.personsApiService
.searchPersonsList(
undefined,
cleanInst,
'cited_by_count',
'desc',
[params.topic],
1,
6,
undefined,
)
.pipe(
switchMap((res) => {
if (res.results && res.results.length > 0) {
return of(res.results);
}
return this.personsApiService
.searchPersonsList(
undefined,
undefined,
'cited_by_count',
'desc',
[params.topic],
1,
6,
undefined,
)
.pipe(map((gRes) => gRes.results || []));
}),
catchError(() => of([])),
);
}),
)
.subscribe((authors) => {
this.recommendedAuthors.set(authors);
this.isSuggestionsLoading.set(false);
});
}
private getCacheKey(params: TrendRequestParams): string {
return JSON.stringify({
searchType: params.searchType,
@@ -93,38 +213,19 @@ export class TrendDataService {
): void {
if (!entityId || searchType === 'all') {
this.topTopicsData.set([]);
this.isTopTopicsLoading.set(false);
return;
}
this.isTopTopicsLoading.set(true);
this.topTopicsError.set(false);
const cleanId = cleanEntityId(entityId);
this.apiService
.getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet(
cleanId,
entityType,
startYear,
endYear,
searchType,
)
.subscribe({
next: (res) => {
const mapped = (res.items || []).map((item) => ({
value: item.count,
name: item.name,
}));
this.topTopicsData.set(mapped);
this.isTopTopicsLoading.set(false);
},
error: (err) => {
console.error('Failed to load top topics:', err);
this.topTopicsError.set(true);
this.isTopTopicsLoading.set(false);
this.topTopicsData.set([]);
},
});
this.topTopicsSubject.next({
cleanId: cleanEntityId(entityId),
entityType,
startYear,
endYear,
searchType,
});
}
/**
@@ -136,24 +237,7 @@ export class TrendDataService {
regionFilter?: string,
): void {
this.isSuggestionsLoading.set(true);
this.apiService
.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(
topic,
regionFilter,
countryFilter,
6,
)
.subscribe({
next: (res: any) => {
this.topSuggestions.set(res || []);
this.isSuggestionsLoading.set(false);
},
error: () => {
this.topSuggestions.set([]);
this.isSuggestionsLoading.set(false);
},
});
this.instSuggestionsSubject.next({ topic, countryFilter, regionFilter });
}
/**
@@ -161,53 +245,6 @@ export class TrendDataService {
*/
loadRecommendedAuthors(topic: string, primaryInstId: string): void {
this.isSuggestionsLoading.set(true);
const cleanInst = cleanEntityId(primaryInstId) || 'I62318514';
this.personsApiService
.searchPersonsList(
undefined,
cleanInst,
'cited_by_count',
'desc',
[topic],
1,
6,
undefined,
)
.subscribe({
next: (res) => {
if (res.results && res.results.length > 0) {
this.recommendedAuthors.set(res.results);
this.isSuggestionsLoading.set(false);
} else {
// Global fallback search across all institutions
this.personsApiService
.searchPersonsList(
undefined,
undefined,
'cited_by_count',
'desc',
[topic],
1,
6,
undefined,
)
.subscribe({
next: (globalRes) => {
this.recommendedAuthors.set(globalRes.results || []);
this.isSuggestionsLoading.set(false);
},
error: () => {
this.recommendedAuthors.set([]);
this.isSuggestionsLoading.set(false);
},
});
}
},
error: () => {
this.recommendedAuthors.set([]);
this.isSuggestionsLoading.set(false);
},
});
this.recAuthorsSubject.next({ topic, primaryInstId });
}
}
@@ -557,49 +557,33 @@ export class UniTrendParentComponent implements OnInit {
}
isTopicEmpty(topic: string): boolean {
const allSeries = this.rawTrendResponse()?.series || [];
const allSeries =
this.trendResponse()?.series || this.rawTrendResponse()?.series || [];
if (allSeries.length === 0) return true;
const series =
this.selectedSearchType() === 'news'
? allSeries.filter((s) => this.seriesTopicName(s.entity_id) === topic)
: allSeries;
if (series.length === 0) return true;
const mapped = this.getMappedTopic(topic);
const startYr = this.startYear();
const endYr = this.endYear();
const cId = cleanEntityId(topic);
for (const s of series) {
if (!s.topic_data) continue;
const keys = [
topic,
mapped,
cId ? `https://openalex.org/${cId}` : '',
cId,
].filter(Boolean);
for (const k of keys) {
const topicItems = s.topic_data[k];
if (topicItems && topicItems.length > 0) {
const sumRaw = topicItems
.filter((y) => y.year >= startYr && y.year <= endYr)
.reduce((acc, curr) => acc + (curr.raw || 0), 0);
if (sumRaw > 0) return false;
}
}
}
return true;
return isTopicEmptyForSeries(
topic,
series,
this.startYear(),
this.endYear(),
(t) => this.getMappedTopic(t),
);
}
findFirstNonEmptyTopic(topics: string[]): string {
const allSeries =
this.trendResponse()?.series || this.rawTrendResponse()?.series || [];
if (!topics || topics.length === 0) return '';
for (const t of topics) {
if (!this.isTopicEmpty(t)) {
return t;
}
}
return topics[0];
return findFirstNonEmptyTopic(
topics,
allSeries,
this.startYear(),
this.endYear(),
(t) => this.getMappedTopic(t),
);
}
isVisible(id: string): boolean {
@@ -903,6 +887,11 @@ export class UniTrendParentComponent implements OnInit {
}
if (resolved.authors && resolved.authors.length > 0) {
this.comparisonAuthors.set(resolved.authors);
const currentUrlAuthors =
this.route.snapshot.queryParamMap.getAll('authors');
if (currentUrlAuthors.length === 0 && type === 'authors') {
this.updateUrlParams();
}
}
if (resolved.treemapNode !== undefined) {
@@ -26,15 +26,42 @@ export function isTopicEmptyForSeries(
seriesList: TrendSeries[],
startYr: number,
endYr: number,
getMappedTopicFn?: (topic: string) => string,
): boolean {
if (!seriesList || seriesList.length === 0) return true;
const mapped = getMappedTopicFn ? getMappedTopicFn(topicName) : topicName;
const cleanId = cleanEntityId(topicName);
const cleanMappedId = cleanEntityId(mapped);
const topicLower = topicName.toLowerCase().trim();
const mappedLower = mapped.toLowerCase().trim();
for (const s of seriesList) {
const topicItems = s.topic_data?.[topicName] || [];
const filtered = topicItems.filter(
(y) => y.year >= startYr && y.year <= endYr,
);
const sumRaw = filtered.reduce((acc, curr) => acc + (curr.raw || 0), 0);
if (sumRaw > 0) return false;
if (!s.topic_data) continue;
const entries = Object.entries(s.topic_data);
for (const [key, topicItems] of entries) {
if (!topicItems || topicItems.length === 0) continue;
const keyLower = key.toLowerCase().trim();
const keyClean = cleanEntityId(key);
const revMapped = getMappedTopicFn
? getMappedTopicFn(key).toLowerCase().trim()
: '';
const isMatch =
keyLower === topicLower ||
keyLower === mappedLower ||
(cleanId && keyClean === cleanId) ||
(cleanMappedId && keyClean === cleanMappedId) ||
(revMapped && (revMapped === topicLower || revMapped === mappedLower));
if (isMatch) {
const sumRaw = topicItems
.filter((y) => y.year >= startYr && y.year <= endYr)
.reduce((acc, curr) => acc + (curr.raw || 0), 0);
if (sumRaw > 0) return false;
}
}
}
return true;
}
@@ -47,10 +74,13 @@ export function findFirstNonEmptyTopic(
seriesList: TrendSeries[],
startYr: number,
endYr: number,
getMappedTopicFn?: (topic: string) => string,
): string {
if (!topics || topics.length === 0) return '';
for (const t of topics) {
if (!isTopicEmptyForSeries(t, seriesList, startYr, endYr)) {
if (
!isTopicEmptyForSeries(t, seriesList, startYr, endYr, getMappedTopicFn)
) {
return t;
}
}
+168 -144
View File
@@ -1,6 +1,6 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { catchError, of, Observable, map, forkJoin } from 'rxjs';
import { catchError, of, Observable, map, forkJoin, switchMap } from 'rxjs';
import {
TrendResponse,
UniversityRankingsService,
@@ -142,13 +142,6 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
return { id: cleanId, name: parts[1] || parts[0] };
});
const instIds =
parsedInstitutions.length > 0
? parsedInstitutions.map((i) => i.id)
: [primaryInstId];
const countryIds = parsedCountries.map((c) => c.id);
const regionIds = parsedRegions.map((r) => r.id);
const authorIds = parsedAuthors.map((a) => a.id);
const apiService = inject(UniversityRankingsService);
const errorService = inject(ErrorService);
const personsService = inject(PersonsService, { optional: true });
@@ -159,148 +152,179 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
const regionFilter =
parsedRegions.length > 0 ? parsedRegions[0].id : undefined;
const currentParams: TrendRequestParams = {
topics,
keywords,
fuzzy,
institutions: instIds,
countries: countryIds,
regions: regionIds,
authors: authorIds,
searchType,
const fetchTrendAndSuggestions = (
authors: CompareItem[],
): Observable<UniTrendResolvedData> => {
const instIds =
parsedInstitutions.length > 0
? parsedInstitutions.map((i) => i.id)
: [primaryInstId];
const countryIds = parsedCountries.map((c) => c.id);
const regionIds = parsedRegions.map((r) => r.id);
const authorIds = authors.map((a) => a.id);
const currentParams: TrendRequestParams = {
topics,
keywords,
fuzzy,
institutions: instIds,
countries: countryIds,
regions: regionIds,
authors: authorIds,
searchType,
};
let trendObs$: Observable<TrendResponse | null>;
if (trendDataService.canReuseCache(currentParams)) {
trendObs$ = of(trendDataService.getCachedResponse(currentParams));
} else {
trendObs$ = apiService
.getTrendApiInseServiceUniversityRankingsTrendGet(
topics,
keywords,
fuzzy,
instIds,
countryIds,
regionIds,
authorIds,
searchType as any,
)
.pipe(
map((res) => {
trendDataService.updateCache(res, currentParams);
return res;
}),
catchError((err) => {
errorService.setError({
statusCode: err?.status || 500,
title: 'Visualisierungs-Fehler',
message: 'Trenddaten konnten nicht geladen werden.',
errorDetails: err?.message || String(err),
});
return of(null);
}),
);
}
const topInstObs$ =
searchType !== 'authors'
? apiService
.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(
primaryTopic,
regionFilter,
countryFilter,
6,
)
.pipe(catchError(() => of([])))
: of([]);
const recAuthorsObs$ =
searchType === 'authors' && personsService
? personsService
.searchPersonsList(
undefined,
primaryInstId,
'cited_by_count',
'desc',
[primaryTopic],
1,
6,
undefined,
)
.pipe(
map((res: any) => res.results || []),
catchError(() => of([])),
)
: of([]);
return forkJoin({
trendResponse: trendObs$,
topSuggestions: topInstObs$,
recommendedAuthors: recAuthorsObs$,
}).pipe(
map(({ trendResponse, topSuggestions, recommendedAuthors }) => {
let initialActiveTopic = primaryTopic;
if (
trendResponse?.series &&
trendResponse.series.length > 0 &&
topics.length > 0
) {
const nonEmptyTopic = topics.find((t) =>
trendResponse.series.some((s) => {
if (!s.topic_data) return false;
const tLower = t.toLowerCase().trim();
const matchingKey = Object.keys(s.topic_data).find((key) => {
const kLower = key.toLowerCase().trim();
return (
kLower === tLower ||
(kLower.startsWith('news_topic_') &&
kLower.slice('news_topic_'.length) === tLower)
);
});
if (!matchingKey) return false;
const yearlyList = s.topic_data[matchingKey];
if (!yearlyList || !Array.isArray(yearlyList)) return false;
const total = yearlyList.reduce(
(sum, item) => sum + (item.raw || 0),
0,
);
return total > 0;
}),
);
if (nonEmptyTopic) {
initialActiveTopic = nonEmptyTopic;
}
}
return {
trendResponse,
searchType,
topics,
keywords,
fuzzy,
institutions: parsedInstitutions,
countries: parsedCountries,
regions: parsedRegions,
authors,
initialActiveTopic,
topSuggestions: topSuggestions as any[],
recommendedAuthors: recommendedAuthors as any[],
treemapNode,
};
}),
);
};
// Check exact parameter keyed cache
let trendObs$: Observable<TrendResponse | null>;
if (trendDataService.canReuseCache(currentParams)) {
trendObs$ = of(trendDataService.getCachedResponse(currentParams));
} else {
trendObs$ = apiService
.getTrendApiInseServiceUniversityRankingsTrendGet(
topics,
keywords,
fuzzy,
instIds,
countryIds,
regionIds,
authorIds,
searchType as any,
if (
searchType === 'authors' &&
parsedAuthors.length === 0 &&
personsService
) {
return personsService
.searchPersonsList(
undefined,
primaryInstId,
'cited_by_count',
'desc',
[primaryTopic],
1,
6,
undefined,
)
.pipe(
map((res) => {
trendDataService.updateCache(res, currentParams);
return res;
}),
catchError((err) => {
errorService.setError({
statusCode: err?.status || 500,
title: 'Visualisierungs-Fehler',
message: 'Trenddaten konnten nicht geladen werden.',
errorDetails: err?.message || String(err),
});
return of(null);
map((res: any) => res.results || []),
catchError(() => of([])),
switchMap((recAuthors) => {
const defaultAuthors: CompareItem[] = recAuthors
.slice(0, 3)
.map((author: any) => ({
id: cleanEntityId(author.id),
name: author.display_name || 'Unbekannt',
}));
return fetchTrendAndSuggestions(defaultAuthors);
}),
);
}
const topInstObs$ =
searchType !== 'authors'
? apiService
.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(
primaryTopic,
regionFilter,
countryFilter,
6,
)
.pipe(catchError(() => of([])))
: of([]);
const recAuthorsObs$ =
searchType === 'authors' && personsService
? personsService
.searchPersonsList(
undefined,
primaryInstId,
'cited_by_count',
'desc',
[primaryTopic],
1,
6,
undefined,
)
.pipe(
map((res: any) => res.results || []),
catchError(() => of([])),
)
: of([]);
return forkJoin({
trendResponse: trendObs$,
topSuggestions: topInstObs$,
recommendedAuthors: recAuthorsObs$,
}).pipe(
map(({ trendResponse, topSuggestions, recommendedAuthors }) => {
let initialActiveTopic = primaryTopic;
if (
trendResponse?.series &&
trendResponse.series.length > 0 &&
topics.length > 0
) {
const nonEmptyTopic = topics.find((t) =>
trendResponse.series.some((s) => {
if (!s.topic_data) return false;
const tLower = t.toLowerCase().trim();
const matchingKey = Object.keys(s.topic_data).find((key) => {
const kLower = key.toLowerCase().trim();
return (
kLower === tLower ||
(kLower.startsWith('news_topic_') &&
kLower.slice('news_topic_'.length) === tLower)
);
});
if (!matchingKey) return false;
const yearlyList = s.topic_data[matchingKey];
if (!yearlyList || !Array.isArray(yearlyList)) return false;
const total = yearlyList.reduce(
(sum, item) => sum + (item.raw || 0),
0,
);
return total > 0;
}),
);
if (nonEmptyTopic) {
initialActiveTopic = nonEmptyTopic;
}
}
if (
searchType === 'authors' &&
parsedAuthors.length === 0 &&
recommendedAuthors?.length
) {
recommendedAuthors.slice(0, 3).forEach((author: any) => {
parsedAuthors.push({
id: cleanEntityId(author.id),
name: author.display_name || 'Unbekannt',
});
});
}
return {
trendResponse,
searchType,
topics,
keywords,
fuzzy,
institutions: parsedInstitutions,
countries: parsedCountries,
regions: parsedRegions,
authors: parsedAuthors,
initialActiveTopic,
topSuggestions: topSuggestions as any[],
recommendedAuthors: recommendedAuthors as any[],
treemapNode,
};
}),
);
return fetchTrendAndSuggestions(parsedAuthors);
};