gpt4 book ai didi

angular - Angular 8 组件中数据访问的奇怪之处

转载 作者:行者123 更新时间:2023-12-04 15:17:01 24 4
gpt4 key购买 nike

我正在开发一个处理 xml 文件并返回接口(interface)数据结构的服务。
起初我以为服务已经正确返回了所有数据,但后来我意识到一些不清楚的地方,特别是当我要读取组件中的数据结构时。
这是我的服务:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { AppConfig } from 'src/app/app.config';
import { forkJoin, Subscription } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class BibliographyParserService {

private editionUrls = AppConfig.evtSettings.files.editionUrls || [];
private bibliographicCitations: Array<BibliographicCitation> = [];
private subscriptions: Array<Subscription> = [];

constructor(
private http: HttpClient,
) {
}

private getHttpCallsOBSStream() {
return this.editionUrls.map((path) => this.http.get(path, { responseType: 'text'}));
}

public getBibliographicCitations(): Array<BibliographicCitation> {
const parser = new DOMParser();
this.subscriptions.push(forkJoin(this.getHttpCallsOBSStream()).subscribe((responses) => {
responses.forEach(response => {
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 = {
authors: 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); }
}
});
});
}));
return this.bibliographicCitations;
}
}

export interface BibliographicCitation {
authors?: HTMLCollectionOf<Element>;
title: string;
date?: Element;
}

这是我的组件:
import { Component, AfterViewInit } from '@angular/core';
import { BibliographyParserService } from 'src/app/services/xml-parsers/bibliography-parser.service';

@Component({
selector: 'evt-bibliography',
templateUrl: './bibliography.component.html',
styleUrls: ['./bibliography.component.scss']
})
export class BibliographyComponent implements AfterViewInit{

constructor(
public bps: BibliographyParserService,
) {
console.log(this.bps.getBibliographicCitations()); // WORKS, return the correct data structure
this.bps.getBibliographicCitations().forEach(console.log); // DOESN'T RETURN ANYTHING!
console.log(this.bps.getBibliographicCitations().length); // RETURN 0
}

ngAfterViewInit() {
(document.querySelectorAll('.cloosingRood')[0] as HTMLElement).onclick = () => {
(document.querySelectorAll('.biblSpace')[0] as HTMLElement).style.display = 'none';
};
}
}

非常奇怪的是这三个日志。我们可以看到它们之间的不同之处。
通过第一个日志,我可以在控制台中看到整个数据结构。
对于第二个,没有任何 react 。
用第三个,长度等于0,这是不正确的,因为如第一个日志所示,数据结构已满......!
我不明白为什么会有这些奇怪的东西。我从 Angular 文档中遗漏了什么吗?
PS:我不想在组件中进行订阅,否则我早就解决了……我想将逻辑与可视化分开,并像我一样在服务中创建数据结构。

最佳答案

这里有两个问题:

  • 您正在混合命令式和响应式(Reactive)编程。

  • 您永远无法知道 forkJoin 何时会发出。因此,您不能确定实例变量 bibliographicCitations当您从 getBibliographicCitations 返回时会更新. In 可以是同步的或异步的。您需要使方法可观察:
    getBibliographicCitations(): Observable<Array<BibliographicCitation>>;

    一种简单的方法是重构方法以设置 Observable。 :
    private refreshSub = new Subject<void>();
    private bibliographicCitations$: Observable<BibliographicCitation[]>;

    refresh(): void {
    this.refreshSub.next();
    }

    private buildObservables(): void {
    this.bibliographicCitations$ = this.refreshSub.pipe(
    switchMap(() => forkJoin(this.getHttpCallsOBSStream()),
    map(responses => {
    // Get all elements from response.
    const elements = responses.reduce((acc, response) => [
    ...acc,
    ...parser.parseFromString(response, 'text/xml').getElementsByTagName('bibl')
    ], [] as Element[]);

    // Use all elements to query for stuff.
    return elements.reduce((acc, element) => {
    if (['author', 'title', 'date'].every(tag => element.getElementsByTagName(tag).length === 0)) {
    return [...acc, { title: element.textContent.replace(/\s+/g, ' ') }];
    } else {
    return [...acc, {
    authors: element.getElementsByTagName('author'),
    title: `${element.getElementsByTagName('title')[0]}`.replace(/\s+/g, ' '),
    date: element.getElementsByTagName('date')[0],
    }];
    }
    }, [] as BibliographicCitation[]);
    })
    shareReplay(1)
    );
    }

    然后你可以为它添加一个 getter 方法 Observable在您的服务中。
    getBibliographicCitations(): Observable<Array<BibliographicCitation>> {
    return this.bibliographicCitations$;
    }

    刷新方法可用于重新触发读取。

    一切就绪后,您可以使用 getBibliographicCitations在组件内部并在那里订阅它。关键是您应该只在您真正准备好使用该值时订阅。存储 observable 的发射是一种反模式。
  • 每次调用 getBibliographicCitations 时,您都会创建新订阅。

  • 每次调用你的方法 getBibliographicCitations一个新的 Subscription被 build 。也就是说,调用3次后,就会有 3 使用自己的订阅操作 DOMParser .而且每一个都会修改实例变量 bibliographicCitations .

    如果您想避免重复订阅,则必须在创建新订阅之前取消订阅以前的订阅。但是,如果您使用上面的代码并设置 Observable,则这些都不是必需的。一次。

    关于angular - Angular 8 组件中数据访问的奇怪之处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59217729/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com