【发布时间】:2021-07-14 21:40:46
【问题描述】:
我正在尝试为链接对象动态构建一个数组。动态地,因为我需要读取 Ngrx Store 并获取参数。 就像在热图中一样
public linksObject = [
{
name: 'Consumption',
link: ['../consumption'],
},
{
name: 'Heatmap',
link: ['../heatmap&res=foo'],
}
];
我有一个构建单个对象的 switchMap,但我需要将它附加到 this.linkObjects
第二个 switchMap 正在获取一个角色数组,例如 ['admin', 'test', 'field_engineer'] 并在 getLinkObjects 内部构建对象:
{name: label, link:['..\ ...']}
pages 只是一个静态标签列表 ['consumption', 'heatmap']
public getLinkObjects(roles: string[]): Observable<any> {
return from(this.pages).pipe(
switchMap(
(page): Observable<ILinksObject> =>
from(roles).pipe(
map((role) => ({
name: page,
link: [`../${page}&role=${role}`],
})),
),
),
);
}
this.fetchRoles()
.pipe(
switchMap((roles: IUserSite[]) => this.getCurrentRoles(roles)),
switchMap((role: string[]) => this.getLinkObjects(role)),
// concat the objects emitted by switchMap
)
.subscribe();
我尝试了以下 3 种方法,但没有奏效:
- 在订阅中添加推送
- 添加水龙头
this.fetchRoles()
.pipe(
switchMap((roles: IUserSite[]) => this.getCurrentRoles(roles)),
switchMap((role: string[]) => this.getLinkObjects(role)),
// concat the objects emitted by switchMap
)
.subscribe(this.linkObjects.push);
this.fetchRoles()
.pipe(
switchMap((roles: IUserSite[]) => this.getCurrentRoles(roles)),
switchMap((role: string[]) => this.getLinkObjects(role)),
tap((role) => this.linkObjects.push(role))
// concat the objects emitted by switchMap
)
.subscribe();
this.fetchRoles()
.pipe(
switchMap((roles: IUserSite[]) => this.getCurrentRoles(roles)),
switchMap((role: string[]) => this.getLinkObjects(role)),
tap(console.log), // this gets printed
reduce((acc, role) => acc.concat(role), this.linksObject),
tap(console.log), // this does not get printed
)
.subscribe(console.log);
我需要帮助指出正确的 rxjs 操作员的使用方向,并帮助排除这两种解决方案不起作用的原因。
【问题讨论】:
标签: angular rxjs observable rxjs-pipeable-operators