[英]Download a text file and assign the text as a string to a variable - Angular 7
我有一個API響應,其中包含指向雲中存儲的文本文件的鏈接。 我想下載文本文件並在Angular應用程序中使用文本作為字符串。
這是我到目前為止做的(不多)
getTextDetails(resultId: string) {
this.http.get(TEXT_DETAILS_URL + resultId).subscribe((res: any) => {
this.saveTextFile(res.textFile);
});
}
// The data is a link to the text file!!
saveTextFile(data) {
const blob = new Blob([data], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
}
任何幫助將不勝感激。
[編輯]
謝謝你的幫助,我不知道那么簡單。 我現在收到一個小問題:
SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad
為了獲取文本文件。 你可以做:
text: string;
getTextDetails(resultId: string) {
this.http.get(TEXT_DETAILS_URL + resultId).subscribe((res: any) => {
//Now get the text from url.
this.http.get(res.textFile).subscribe(text: any) {
this.text = text;
}
});
}
現在,您可以在html模板中顯示此文本。
<p ngIf*="text"> {{ text }} </p>
據我所知,有兩個API調用。 第一個API調用返回文本文件的路徑。 您使用此路徑進行另一個API調用以獲取文件的實際內容。
如果我的理解不正確,請更正。
如果我的理解是正確的,試試看:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { switchMap } from 'rxjs/operators';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
constructor(private http: HttpClient) {}
ngOnInit() {
this.getFileData()
.subscribe(response => console.log(response));
}
getFileData() {
return this.http.get('/assets/filePath.json')
.pipe(
switchMap((response: any) => this.http.get(response.pathToFile, {
responseType: 'text'
}))
);
}
}
注意:請理解我正在使用本地托管的JSON文件的響應,該文件再次指向本地托管的文本文件。 此外,您必須將第二個API調用的responseType
指定為text
。
這是你的參考的工作樣本StackBlitz 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.