I'm newbie with Angular 8. I'm creating a method within a service that allows me to return a dynamically constructed data structure.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { AppConfig } from 'src/app/app.config';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class BibliographyParserService {
private editionUrls = AppConfig.evtSettings.files.editionUrls || [];
private bibliographicCitations: Array<BibliographicCitation> = [];
constructor(
private http: HttpClient,
) {
}
public getBibliographicCitations() {
const parser = new DOMParser();
this.editionUrls.forEach((path) => {
this.http.get(path, { responseType: 'text' }).pipe(map((response: string) => {
Array.from(parser.parseFromString(response, 'text/xml').getElementsByTagName('bibl')).forEach(citation => {
if (citation.getElementsByTagName('author').length === 0 &&
citation.getElementsByTagName('title').length === 0 &&
citation.getElementsByTagName('date').length === 0) {
const interfacedCitation: BibliographicCitation = {
title: citation.textContent.replace(/\s+/g, ' '),
};
if (!this.bibliographicCitations.includes(interfacedCitation)) { this.bibliographicCitations.push(interfacedCitation); }
} else {
const interfacedCitation: BibliographicCitation = {
author: citation.getElementsByTagName('author'),
title: String(citation.getElementsByTagName('title')[0]).replace(/\s+/g, ' '),
date: citation.getElementsByTagName('date')[0],
};
if (!this.bibliographicCitations.includes(interfacedCitation)) { this.bibliographicCitations.push(interfacedCitation); }
}
});
this.bibliographicCitations.forEach(biblCit => {
console.log(((biblCit.author === undefined) ? '' : biblCit.author),
((biblCit.title === undefined) ? '' : biblCit.title),
((biblCit.date === undefined) ? '' : biblCit.date));
});
}),
);
});
// THIS IS RETURNED EMPTY IN THE COMPONENT WHEN ACTUALLY IT IS FULL!
return this.bibliographicCitations;
}
}
export interface BibliographicCitation {
author?: HTMLCollectionOf<Element>;
title: string;
date?: Element;
}
In the documentation I consulted I noticed that there is no such "complex" example, in the sense that the data I want to take is inside an http
call, which in turn is inside a loop! And I obviously want to return them when the cycle is completed.
If I call the method outside with console.log(this.bps.getBibliographicCitations())
, it now returns an empty data structure:
[]
length: 0
__proto__: Array(0)
I would like to know if there was a way to return the data by avoiding to immediately subscribe
into the service.