我的资产文件夹中有两个用于存储重要密钥的文本文件: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 });
}
}
答案 0 :(得分:0)
我使用 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;
};
});
下载文件后,文件阅读器读取文件内容并使用文件内容更新组件属性。