问题
My service returns object with events and count properties. Right now I need to do two requests. First to get events and second to get events count. I'd like to use Observables in component and async pipe in the template. I know how to achieve it subscribing to the service in the component, but I'd like to understand how to map both events and count to an observables with one request. What RxJs operator should I use ?
import { Component, OnInit } from '@angular/core';
import { Event } from '../event.model';
import { Observable } from 'rxjs';
import { EventsService } from '../events.service';
import { first, map, take } from 'rxjs/operators';
@Component({
selector: 'app-events-list',
templateUrl: './events-list.component.html',
styleUrls: ['./events-list.component.css']
})
export class EventsListComponent implements OnInit {
events: Event[];
a$: Observable<Event[]>;
total$: Observable<number>;
pageSize: number = 100;
currentPage: number = 1;
constructor(private eventsService: EventsService) { }
ngOnInit(): void {
this.a$ = this.eventsService.getEvents(this.pageSize, this.currentPage).pipe(
map(results => results.events)
);
this.total$ = this.eventsService.getEvents(this.pageSize, this.currentPage).pipe(
map(results => results.count)
);
}
}
回答1:
It appears the response is already an object containing the properties events and count. So you could initialize a single variable (eg. events$) in the controller and use it in the template with async pipe.
You could also use ng-container tag along with *ngIf's as construct to reuse the emissions from the observable. The ng-container does not contribute to additional tags and are commented out in the generated DOM.
Try the following
Controller
export class EventsListComponent implements OnInit {
events: Event[];
events$: Observable<any>;
pageSize: number = 100;
currentPage: number = 1;
constructor(private eventsService: EventsService) { }
ngOnInit(): void {
this.events$ = this.eventsService.getEvents(this.pageSize, this.currentPage);
}
}
Template
<ng-container *ngIf="(events$ | async) as events">
Event: {{ events?.events | json }}
Count: {{ events?.count }}
<sample-comp [sampleInput]="events?.events"></sample-comp>
</ng-container>
I've used safe navigation operator ?. to avoid any undefined errors and json pipe to render the events.events object.
回答2:
Alternatively to Michael D's solution you can do this
const events$ = this.eventsService.getEvents(this.pageSize, this.currentPage).pipe(
shareReplay(1),
);
this.a$ = events$.pipe(
map(results => results.events)
);
this.total$ = events$.pipe(
map(results => results.count)
);
来源:https://stackoverflow.com/questions/64502955/angular-rxhj-map-multiple-object-properties