首页 > 解决方案 > Angular:从资产文本文件中加载值

问题描述

我的资产文件夹中有两个文本文件,用于存储重要密钥: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 });
   }
}

标签: angularfile-ioassets

解决方案


我使用 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;
        };
      });

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


推荐阅读