【问题标题】:Angular: Load value from asset text fileAngular:从资产文本文件中加载值
【发布时间】:2020-07-06 18:03:42
【问题描述】:

我的资产文件夹中有两个用于存储重要密钥的文本文件:apiKey.txt 和 appId.t​​xt。这些都只包含纯文本

我正在使用 http 客户端来检索它们,但它们仍然注册为未定义。谁能看到我错过了什么?

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
//import { iDynamicsPostUsers } from '../models/dynamics-post';

@Injectable({
  providedIn: 'root'
})
export class AirtableService {
  private apiUrl = 'https://api.airtable.com/v0/';
  protected apiKey: string;
  protected appId: string;

  constructor(private http: HttpClient) {
    this.http.get('assets/apiKey.txt', { responseType: 'text'}).subscribe(data => { this.apiKey = data });
    this.http.get('assets/appId.txt', { responseType: 'text'}).subscribe(data => { this.appId = data });
   }
}

【问题讨论】:

  • 您的代码对我有用。您绝对应该检查 DevTools 网络选项卡并直接在浏览器中试用该 URL,例如。 G。 http://localhost:4200/assets/apiKey.txt.
  • 当我直接在浏览器中尝试时,该 url 有效。虽然在我的 Angular 应用程序中仍然显示为未定义
  • DevTools 网络面板说什么?它是否显示正确的请求?您是否为 HttpClient 使用任何拦截器?
  • 网络面板显示对每个文件的 3 次调用,所有这些调用都返回 304。响应显示正确的返回值,但在角度应用程序中仍未定义
  • 我真的不知道什么不适合你。见这里:stackblitz.com/edit/angular-ivy-lrv3ra

标签: angular file-io assets


【解决方案1】:

我使用 FileReader:

this.http.get('assets/faq.txt', { responseType: 'blob', observe: 'response' })
  .subscribe((value: HttpResponse<Blob>) => {
    const data = new Blob([value.body as Blob], {type: value.body?.type});
    const reader = new FileReader();
    reader.readAsText(data);

    reader.onload = (content) => {
      const textInFile = reader.result as string;
    };
  });

@Darkreaper 很遗憾,但在这种情况下你不能。可以这样发布。

首先,您从资产或远程服务器加载文件。您可以将此逻辑封装在服务或组件中,没关系。

  public downloadFile(url: string): Observable<Blob> {
    return this.http.get('assets/faq.txt', { responseType: 'blob', observe: 'response' })
      .pipe((file:  HttpResponse<Blob>) => {
        return new Blob([value.body as Blob], {type: value.body?.type});
      });
  }

在组件中,您可以将它与文件阅读器一起使用:

  public ngOnInit(): void {
    this.downloadFile(url)
      .subscribe((blob: Blob) => {
        const reader = new FileReader();
        reader.readAsText(blob);

        reader.onload = () => {
          this.componentVar = reader.result;
        };
      });

下载文件后,文件阅读器读取文件内容并使用文件内容更新组件属性。

【讨论】:

  • 我如何将它构造为一个函数,然后我可以在其中传入文件名并让它返回一个包含 textInFile 的 Observable
  • 获取“类型参数 '(value: HttpResponse) => Blob' 不可分配给类型参数 'OperatorFunction, Blob>' 的错误。参数 'value' 和 'source' 不兼容。”在以下部分 .pipe((file: HttpResponse) => {
猜你喜欢
  • 2022-01-21
  • 2019-02-20
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 2012-09-05
  • 1970-01-01
相关资源
最近更新 更多