如何在角度应用程序中从 YAML 文件(保存在我的 PC 中)读取数据?



我是角度和Web开发的新手。我想将一些数据从 YAML 文件获取到我的角度应用程序中。该文件包含图像的元数据。如何上传 YAML 文件,以便我可以从 YAML 文件中读取一些值。我需要在我的应用程序中获取分辨率值。 谢谢。

image: logistikhalle5.png
resolution: 0.007
origin: [0.0, 0.0, 0.000000]
negate: 0
occupied_thresh: 0.165
free_thresh: 0.001

您可以使用 Angular 的 HttpClient Module 来请求(或多或少(任何 Web 资源。此外,您可以从某些项目目录(例如资产(加载本地资源。不幸的是,与例如 JSON 格式不同,您必须在检索纯文本后手动解析YAML 文件。

作为起点,您还应该学习有关如何在 Angular 中使用可观察量和依赖注入 (DI( 的基础知识。可观察量用于处理异步任务(如 HTTP 请求(,而 DI 可帮助您创建可在多个组件中使用的服务实例。

此示例代码提供名为YamlService的服务。它的fetchYaml()方法将从您的资产目录中请求本地资源,并将纯文本响应转换为简单的JavaScript对象。

@Injectable()
export class YamlService {
// the constructor injects the HttpClient service
constructor(private http: HttpClient) {
this.fetchYaml('example.yaml');
}
public fetchYaml(fileName) {
// if you wonder about the string syntax, read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
this.http.get(`/assets/${fileName}`, { responseType: 'text' }).subscribe(response => {
let lines: string[] = response.split('n');  // create array where each YAML line is one entry
let object = {};
lines.forEach((line: string) => {
let delimiter = line.indexOf(':');  // find the colon position inside the line string 
let key = line.substr(0, delimiter - 1);  // extract the key (everything before the colon)
let value = line.substr(delimiter + 1);  // extract the value (everything after the colon)
object[key] = value;  // add a new key-value pair to the object
});
});
}
}

最新更新