如何使用解析器获取模型对象数组?

时间:2019-06-03 13:33:09

标签: angular

我使用解析器从服务器获取数据

import {Resolve, ActivatedRoute} from "@angular/router";
import {Observable} from "rxjs";
import {RouterStateSnapshot} from "@angular/router";
import {ActivatedRouteSnapshot} from "@angular/router";
import {Injectable} from "@angular/core";
import {HttpClient, HttpRequest} from "@angular/common/http";
import {Town} from "../_models/town";

@Injectable()
export class TownsListResolver implements Resolve<any>{

	constructor(private http: HttpClient,private activatedRoute: ActivatedRoute) {
	}

	resolve(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<Town[]> {
		return this.http.get('/api/towns');
	}
}

我不会像这样转换对象数组:

data['towns']['models'].forEach((item) => {
            this.townsList.push(item);
        });

我应该使用哪个rxJs或基本角度函数来解决我的问题?

2 个答案:

答案 0 :(得分:1)

我将简单地执行以下操作:

resolve(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<Town[]> {
    return this.http.get('/api/towns').pipe(
        map(p => p['towns']['models'])
    );
}

那样,您将继续公开一个Observable。

答案 1 :(得分:0)

您可以使用tap()

例如:

.pipe(
 tap(data => this.townsList = [...data['towns']['models']]
)