How to get array of model objects using resolver?

I use resolver to get data from server

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');
	}
}

and i wont to convert array of objects like this :

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

which rxJs or basic angular functions i should use to solve my problem?

Upvotes: 0

Views: 443

Answers (2)

Deblaton Jean-Philippe
Deblaton Jean-Philippe

Reputation: 11388

I would simply do the following :

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

That way, you keep on exposing an Observable.

Upvotes: 1

Kamil Augustyniak
Kamil Augustyniak

Reputation: 429

You can use tap().

For example:

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

Upvotes: 0

Related Questions