Rxjs 转换 API 结果 可观察到服务函数中的另一个可观察



我有一个加载程序服务,其结果是Observable<string>其中包含一个CSV文件。每行代表一个不同的实体(例如(person对象,逗号分隔的部分表示人的属性,例如id、年龄、姓名等。

加载程序服务功能为:

loadtTextFile(path: string): Observable<string> 

loadAllPerson服务功能为:

loadAllPerson(): Observable<Array<Person>> 

我想在包装器loadAllPerson中调用loadtTextFile,其中所需的输出是:Observable<Array<Person>>

如何确保服务仅在 CSV 的所有行都解析为结果Observable<Array<Person>>时才返回?

可能一开始我们应该等待加载程序服务结果,然后将其解析为 Person 数组并以Observable<Array<Person>>返回结果

下面的代码部分将内容分析到Person Array中,其中contentObservable是一个Observable<string>

const contentObservable = this.fileLoaderService.loadtTextFile();
contentObservable.mapTo(fileContent => {
const rowsOfContent = fileContent.split('n');
rowsOfContent.forEach((row: string) => {
const cols = row.split(',');
// has valid numeric value of id and age?
if (!Number.isNaN(+cols[0]) && !Number.isNaN(+cols[3])) {
const person = new Person(+cols[0], cols[1], cols[2], +cols[3], cols[4],
cols[5], cols[6], cols[7], new Date(cols[8]));
personData.push(person);
}
});
console.log(JSON.stringify(personData));
});

map运算符是你的朋友。尝试如下:

loadAllPerson(): Observable<Person[]> {
return loadTextFile(PATH).pipe(
map((csv: string) =>
csv.split('n')
.map((rows: string[]) => rows.map((row: string) => row.split(',')))
.map((table: string[][]) => 
table.filter((cols: string[]) => !Number.isNaN(+cols[0]) && !Number.isNaN(+cols[3]))
.map((cols: string[]) => new Person(+cols[0], cols[1], cols[2], +cols[3], cols[4], cols[5], cols[6], cols[7], new Date(cols[8])))
)
)),
);
}

最新更新