Angular 可选异步管道或默认管道

Angular 可选异步管道或默认管道,angular,rxjs,pipe,Angular,Rxjs,Pipe,如果观察值未定义,我没有找到更好的方法读取默认值。 而不是为模板中的每个可观察属性编写这部分代码 <div *ngIf="!property.visible$ ? property.visible || true : (property.visible$ | async">Test</div> 或者你有其他想法吗 注: 同样,也可以在ts文件中使用此逻辑编写函数,但不要认为在每次更新html

如果观察值未定义,我没有找到更好的方法读取默认值。
而不是为模板中的每个可观察属性编写这部分代码

            <div *ngIf="!property.visible$
              ? property.visible || true
              : (property.visible$ | async">Test</div>
或者你有其他想法吗

注:


同样,也可以在ts文件中使用此逻辑编写函数,但不要认为在每次更新html时采用(1)订阅值对性能是一个好主意,我们需要读取可观察值

您可以创建自己的可观察值,然后使用
async
管道订阅:

this.visible$ = of({}).pipe(switchMap(() => {
 if (this.property.visible$) return this.property.visible$;

 return of(this.property.visible);
}));



请查看此

您可以创建自己的observable,然后使用
async
管道订阅:

this.visible$ = of({}).pipe(switchMap(() => {
 if (this.property.visible$) return this.property.visible$;

 return of(this.property.visible);
}));



请看一下这个

可以使用这个扩展异步管道

import { Pipe, PipeTransform } from '@angular/core';
import { Observable, of } from 'rxjs';

@Pipe({ name: 'default$' })
export class Default$Pipe implements PipeTransform {
  transform(
    value$: Observable<any> | undefined,
    defaultValue: any
  ): Observable<any> {
    return value$ ? value$ : of(defaultValue);
  }
} 

 property.visible$| default$ : property.visible || false | async  
从'@angular/core'导入{Pipe,PipeTransform};
从'rxjs'导入{可观察的};
@管道({name:'default$'})
导出类默认$Pipe实现了PipeTransform{
转化(
价值$:可观察|未定义,
默认值:任意
):可见{
返回值$?值$:的(默认值);
}
} 
property.visible$| default$:property.visible | | false | async

可以使用此扩展异步管道

import { Pipe, PipeTransform } from '@angular/core';
import { Observable, of } from 'rxjs';

@Pipe({ name: 'default$' })
export class Default$Pipe implements PipeTransform {
  transform(
    value$: Observable<any> | undefined,
    defaultValue: any
  ): Observable<any> {
    return value$ ? value$ : of(defaultValue);
  }
} 

 property.visible$| default$ : property.visible || false | async  
从'@angular/core'导入{Pipe,PipeTransform};
从'rxjs'导入{可观察的};
@管道({name:'default$'})
导出类默认$Pipe实现了PipeTransform{
转化(
价值$:可观察|未定义,
默认值:任意
):可见{
返回值$?值$:的(默认值);
}
} 
property.visible$| default$:property.visible | | false | async

https://ultimatecourses.com/blog/angular-ngif-async-pipe 
可能是您的情况。
https://ultimatecourses.com/blog/angular-ngif-async-pipe 
可能是您的情况。。