angular - Angular:从资产文本文件中加载值
问题描述
我的资产文件夹中有两个文本文件,用于存储重要密钥:apiKey.txt 和 appId.txt。这些都只包含纯文本
我正在使用 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 });
}
}
解决方案
我使用 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;
};
});
下载文件时,文件阅读器读取它的内容并使用文件内容更新组件属性。
推荐阅读
- java - OHttpClient 获取具有有效 I.CA 证书的请求
- ios - 在 UISearchBar 中过滤撇号(特殊字符) - Swift,Xcode
- dictionary - Ansible - 如何从字典中检索值,在额外的变量中传递列表
- r - 在 R 中过滤具有重复行的数据集
- python - 无法导入模块 pyautogui
- asp.net - 在性能监视器中连接网站其 w3wp#X 进程
- java - 使用 dfs 确定给定树是否是子树
- docker - 如何防止来自 docker exec 的无密码登录?
- opencv - 在 OpenCV 中切换 640x480 和 640x360 分辨率
- reactjs - React - 在 useEffect 挂钩中使用 ContextAPI 中的函数缺少依赖项警告