角RXHJ映射多个对象属性 [英] Angular RXHJ map multiple object properties

查看:75
本文介绍了角RXHJ映射多个对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务返回具有事件和计数属性的对象.现在,我需要做两个请求.首先获取事件,其次获取事件计数.我想在模板的组件和异步管道中使用Observables.我知道如何通过订阅组件中的服务来实现它,但是我想了解如何通过一个请求将两个事件都映射并计数到一个可观察对象.我应该使用哪个RxJs运算符?

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

 }

 }

推荐答案

似乎响应已经是一个包含属性 events count 的对象.因此,您可以在控制器中初始化单个变量(例如 events $ ),并通过 async 管道在模板中使用它.

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.

您还可以将 ng-container 标记与 * ngIf as 构造一起使用,以重用可观察对象的发射. ng-container 不会添加其他标签,并且会在生成的DOM中被注释掉.

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.

尝试以下

控制器

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

模板

<ng-container *ngIf="(events$ | async) as events">
  Event: {{ events?.events | json }}
  Count: {{ events?.count }}
  
  <sample-comp [sampleInput]="events?.events"></sample-comp>
</ng-container>

我使用了安全的导航操作符?.来避免任何 undefined 错误和 json 管道来呈现 events.events对象.

I've used safe navigation operator ?. to avoid any undefined errors and json pipe to render the events.events object.

这篇关于角RXHJ映射多个对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆