问题
我正在通过角度服务从 PouchDB 检索文档。文档以下列格式检索:
- {
- "_id":"segments",
- "_rev":"1-4f0ed65cde23fe724db13bea1ae3bb13",
- "segments":[
- { "name":"Aerospace" },
- { "name":"Auto repair" },
- { "name":"Commercial" },
- { "name":"Education" },
- { "name":"Energy" },
- { "name":"Farm/ranch" },
- { "name":"Furniture" },
- { "name":"Heavy Equipment" },
- { "name":"Hobbyist" },
- { "name":"Infrastructure" },
- { "name":"Luxury/Leisure" },
- { "name":"Military" },
- { "name":"MUP" },
- { "name":"Processing" },
- { "name":"Rail" },
- { "name":"Transportation" }
- ]}
复制代码
我想将它映射到一个新数组,如下所示:
- [
- { value: "Aerospace", viewValue: "Aerospace" },
- { value: "Auto Repair", viewValue: "Auto Repair" },
- { value: "Commercial", viewValue: "Commercial" }
- ...
- ]
复制代码
为此,我在我的服务中尝试了以下代码:
- getSegments(): Observable<any[]> {
- return from(this.database.get('segments'))
- .pipe(
- map((results) => results.segments)
- );
- }
复制代码
我将组件中的数组转换为:
- segments: SegmentsLookup[] = [];
- ...
- this.lookupDbService.getSegments()
- .subscribe(data => {
- data.forEach(element => {
- this.segments.push({value: element.name, viewValue: element.name});
- });
- });
复制代码
这可行,但我知道有一种方法可以将其正确映射回服务代码。此外,当这样做时,编译器会抱怨“结果”。段'陈述'属性'段'类型 {} 上不存在。
如何将检索到的数据映射到服务的“getSegments”中的所需数组?方法?
回答
您可以分两步执行转换:
- let transformedData = observableData.pipe(
- map(data => {
- console.log(data, data.segments.length);
- return data.segments.map(element => {
- return { value: element["name"], viewValue: element["name"] };
- });
- })
- );
- transformedData.subscribe(data => {
- this.mylist = data;
- });
复制代码
|