Javascript 如何在angular应用程序中从YAML文件(保存在PC中)读取数据?
我对angular和web开发还不熟悉。我想从YAML文件中获取一些数据到我的angular应用程序中。该文件包含图像的元数据。如何上载YAML文件,以便从YAML文件中读取少量值。我需要在应用程序中获得分辨率的值。 多谢各位Javascript 如何在angular应用程序中从YAML文件(保存在PC中)读取数据?,javascript,angular,typescript,yaml,Javascript,Angular,Typescript,Yaml,我对angular和web开发还不熟悉。我想从YAML文件中获取一些数据到我的angular应用程序中。该文件包含图像的元数据。如何上载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 您可以使用来请求或多
image: logistikhalle5.png
resolution: 0.007
origin: [0.0, 0.0, 0.000000]
negate: 0
occupied_thresh: 0.165
free_thresh: 0.001
您可以使用来请求或多或少的任何web资源。此外,您还可以从某些项目目录(如i)加载本地资源。E资产不幸的是,与e。G对于JSON格式,您必须在检索纯文本后手动解析YAML文件
作为起点,您还应该学习如何在Angular中使用和DI的基础知识。Observable用于处理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
});
});
}
}
您希望您的用户上载他们的yaml文件,还是希望所有用户都读取您计算机中持久存在的yaml文件?后一个有点困难,你可以理解为什么我希望用户上传一个png图像和一个与该png相关的yaml文件。然后我想给他显示图像和它的分辨率值,它在yaml文件中@克里斯蒂安·特拉·纳尤让我很容易理解。它起作用了。非常感谢你。