rxjs/operators#defaultIfEmpty TypeScript Examples
The following examples show how to use
rxjs/operators#defaultIfEmpty.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: my-trades.service.ts From rubic-app with GNU General Public License v3.0 | 6 votes |
private getBridgeTransactions(): Observable<TableTrade[]> {
return this.bridgeApiService.getUserTrades(this.walletAddress).pipe(
switchMap(async trades =>
(await Promise.all(trades.map(trade => this.prepareBridgeData(trade)))).filter(Boolean)
),
mergeMap(bridgeTrades => {
const sources: Observable<HashPair>[] = bridgeTrades.map(trade => {
return of({
fromTransactionHash: trade.fromTransactionHash,
toTransactionHash: trade.toTransactionHash
});
});
return forkJoin(sources).pipe(
map((txHashes: HashPair[]) =>
txHashes.map(({ fromTransactionHash, toTransactionHash }, index) => ({
...bridgeTrades[index],
fromTransactionHash,
toTransactionHash
}))
),
defaultIfEmpty([])
);
}),
catchError((err: unknown) => {
console.debug(err);
this._warningHandler$.next();
return of([]);
})
);
}
Example #2
Source File: file-system.service.ts From mylog14 with GNU General Public License v3.0 | 6 votes |
getJsonData(filename: string, parse = true, dir = FilesystemDirectory.Data): Observable<any> {
const readFile$ = defer(() => from(Filesystem.readFile({
encoding: this.defaultEncoding,
path: filename,
directory: dir,
})));
return readFile$
.pipe(
catchError(() => of({ data: null })),
map(readResult => readResult.data),
filter(data => data != null),
defaultIfEmpty('{}'),
map(data => parse ? JSON.parse(data) : data),
);
}
Example #3
Source File: emote-card.component.ts From App with MIT License | 6 votes |
getBorderColor(): Observable<Color> {
return scheduled([
this.emote?.isGlobal().pipe(map(b => ({ b, type: 'global' }))),
this.emote?.isChannel().pipe(map(b => ({ b, type: 'channel' }))),
], asapScheduler).pipe(
switchMap(value => value ?? EMPTY),
filter(({ b }) => b === true),
defaultIfEmpty({ b: false, type: 'none' }),
take(1),
map(o => o.type as 'global' | 'channel'),
map(type => (type !== null ? ({
global: this.globalBorderColor,
channel: this.channelBorderColor
})[type] as Color : this.borderColor))
);
}
Example #4
Source File: emote-list.component.ts From App with MIT License | 6 votes |
getEmotes(page = 0, options?: Partial<RestV2.GetEmotesOptions>): Observable<EmoteStructure[]> {
this.emotes.next([]);
this.newPage.next(page);
const timeout = setTimeout(() => this.loading.next(true), 1000);
const cancelSpinner = () => {
this.loading.next(false);
clearTimeout(timeout);
};
const size = this.calculateSizedRows();
return this.restService.awaitAuth().pipe(
switchMap(() => this.restService.v2.SearchEmotes(
(this.pageOptions?.pageIndex ?? 0) + 1,
Math.max(EmoteListComponent.MINIMUM_EMOTES, size ?? EmoteListComponent.MINIMUM_EMOTES),
options ?? this.currentSearchOptions
)),
takeUntil(this.newPage.pipe(take(1))),
tap(res => this.totalEmotes.next(res?.total_estimated_size ?? 0)),
delay(200),
map(res => res?.emotes ?? []),
mergeAll(),
map(data => this.dataService.add('emote', data)[0]),
toArray(),
defaultIfEmpty([] as EmoteStructure[]),
tap(() => cancelSpinner()),
catchError(() => defer(() => cancelSpinner()))
) as Observable<EmoteStructure[]>;
}
Example #5
Source File: emote-list.component.ts From App with MIT License | 6 votes |
ngAfterViewInit(): void {
// Get persisted page options?
this.route.queryParamMap.pipe(
defaultIfEmpty({} as ParamMap),
map(params => {
return {
page: params.has('page') ? Number(params.get('page')) : 0,
search: {
sortBy: params.get('sortBy') ?? 'popularity',
sortOrder: params.get('sortOrder'),
globalState: params.get('globalState'),
query: params.get('query'),
submitter: params.get('submitter'),
channel: params.get('channel')
}
};
}),
tap(() => setTimeout(() => this.skipNextQueryChange = false, 0)),
filter(() => !this.skipNextQueryChange)
).subscribe({
next: opt => {
const d = {
pageIndex: !isNaN(opt.page) ? opt.page : 0,
pageSize: Math.max(EmoteListComponent.MINIMUM_EMOTES, this.calculateSizedRows() ?? 0),
length: 0,
};
this.updateQueryParams(true);
this.currentSearchOptions = opt.search as any;
this.paginator?.page.next(d);
this.pageOptions = d;
}
});
this.pageSize.next(this.calculateSizedRows() ?? 0);
}
Example #6
Source File: emote.structure.ts From App with MIT License | 6 votes |
/**
* Get the emote's alias, per the client user or the user they are editing
*/
getAlias(): Observable<string> {
const client = this.getRestService()?.clientService;
if (!client) {
return of('');
}
return of(client.isImpersonating).pipe(
switchMap(isEditor => iif(() => isEditor === true,
client.impersonating.pipe(take(1)),
of(client)
)),
map(usr => usr as UserStructure),
switchMap(usr => from(usr.getEmoteAliases())),
mergeAll(),
filter(alias => alias.emoteID === this.id),
map(alias => alias.name),
defaultIfEmpty('')
);
}
Example #7
Source File: migration.service.ts From capture-lite with GNU General Public License v3.0 | 6 votes |
generateAndUpdateSignatureForUnversionedProofs$() {
return this.proofRepository.all$.pipe(
first(),
map(proofs => proofs.filter(proof => !proof.signatureVersion)),
concatMap(proofs =>
forkJoin(
proofs.map(proof => this.collectorService.generateSignature(proof))
).pipe(defaultIfEmpty(proofs))
),
concatMap(proofs =>
forkJoin(
proofs.map(proof =>
this.diaBackendAssetRepository.updateCaptureSignature$(proof)
)
).pipe(
defaultIfEmpty(),
concatMap(() =>
this.proofRepository.update(
proofs,
(x, y) => getOldProof(x).hash === getOldProof(y).hash
)
)
)
)
);
}
Example #8
Source File: record-repository.service.ts From mylog14 with GNU General Public License v3.0 | 5 votes |
getAll(): Observable<Record[]> {
return this.getMetas()
.pipe(
switchMap(metas => forkJoin(metas.map(meta => this.get(meta)))),
defaultIfEmpty([]),
);
}
Example #9
Source File: user.structure.ts From App with MIT License | 5 votes |
hasPermission(flag: keyof typeof DataStructure.Role.Permission): Observable<boolean> {
return this.data$(this.getRole().pipe(
switchMap(role => role.getAllowed()),
map(allowed => BitField.HasBits64(allowed, DataStructure.Role.Permission[flag]) || BitField.HasBits64(allowed, DataStructure.Role.Permission.ADMINISTRATOR)),
defaultIfEmpty(false)
), false);
}
Example #10
Source File: index.tsx From jetlinks-ui-antd with MIT License | 4 votes |
TenantDevice: React.FC<Props> = (props) => { const initState: State = { searchParam: { pageSize: 10, sorts: { order: "descend", field: "createTime" } }, productList: [], deviceData: {}, }; const [searchParam, setSearchParam] = useState(initState.searchParam); const [deviceData, setDeviceData] = useState(initState.deviceData); const [spinning, setSpinning] = useState(true); const statusMap = new Map(); statusMap.set('online', <Tag color="#87d068">在线</Tag>); statusMap.set('offline', <Tag color="#f50">离线</Tag>); statusMap.set('notActive', <Tag color="#1890ff">未激活</Tag>); const handleSearch = (params?: any) => { setSearchParam(params); apis.deviceInstance.list(encodeQueryParam(params)) .then((response: any) => { if (response.status === 200) { setDeviceData(response.result); } setSpinning(false); }) .catch(() => { }) }; const columns: ColumnProps<DeviceInstance>[] = [ { title: 'ID', dataIndex: 'id', }, { title: '设备名称', dataIndex: 'name', }, { title: '产品名称', dataIndex: 'productName', }, { title: '状态', dataIndex: 'state', width: '90px', render: record => record ? statusMap.get(record.value) : '', filters: [ { text: '未激活', value: 'notActive', }, { text: '离线', value: 'offline', }, { text: '在线', value: 'online', }, ], filterMultiple: false, }, ]; useEffect(() => { handleSearch(searchParam); }, []); const onTableChange = ( pagination: PaginationConfig, filters: any, sorter: SorterResult<DeviceInstance>,) => { setSpinning(true); let { terms } = searchParam; if (filters.state) { if (terms) { terms.state = filters.state[0]; } else { terms = { state: filters.state[0], }; } } handleSearch({ pageIndex: Number(pagination.current) - 1, pageSize: pagination.pageSize, terms, sorts: sorter, }); }; const service = new Service(''); const [data, setData] = useState<any[]>([]); const user = JSON.parse(localStorage.getItem('user-detail') || '{}'); const tenantId = (user.tenants || []).filter((i: any) => i.mainTenant)[0]?.tenantId; const tenantAdmin = (user.tenants || []).filter((i: any) => i.mainTenant)[0]?.adminMember; const getProduct = (userId: string) => service.assets.productNopaging(encodeQueryParam({ terms: { id$assets: JSON.stringify({ tenantId: tenantId, assetType: 'product', memberId: userId, }), } })); const getDeviceState = (product: any, userId: string) => service.assets.instanceNopaging(encodeQueryParam({ terms: { productId: product.id, // id$assets: JSON.stringify({ // tenantId: tenantId, // assetType: 'device', // memberId: userId, // }), } })).pipe( groupBy((instance: any) => instance.state.value), mergeMap(group$ => group$.pipe( count(), map(count => { let v: any = {}; v[group$.key] = count; return v; }), )), map(state => ({ productName: product.name, online: state.online || 0, offline: state.offline || 0 })), defaultIfEmpty({ productName: product.name, 'online': 0, 'offline': 0 }), ); const getAlarmCount = (productId: string, userId: string) => service.alarm.count(encodeQueryParam({ terms: { // deviceId$assets: JSON.stringify({ // tenantId: tenantId, // assetType: 'device', // memberId: userId, // }), productId: productId, } })); useEffect(() => { // todo 查询租户 if (tenantId) { service.member.queryNoPaging({}) .pipe( flatMap((i: any) => getProduct(i.userId) .pipe( flatMap((product: any) => zip(getDeviceState(product, i.userId), getAlarmCount(product.id, i.userId))), map(tp2 => ({ userId: i.userId, name: i.name, key: `${i.userId}-${randomString(7)}`, ...tp2[0], alarmCount: tp2[1] })), defaultIfEmpty({ userId: i.userId, name: i.name, key: `${i.userId}` }) )), toArray(), map(list => list.sort((a, b) => a.userId - b.userId)), ).subscribe((result) => { setData(result); }); } }, [tenantId]); const test: string[] = []; const columns2 = [ { title: '成员', dataIndex: 'name', render: (text, row, index) => { test.push(text); return { children: text, props: { rowSpan: test.filter(i => i === text).length > 1 ? 0 : data.filter(i => i.name === text).length, }, }; }, }, { title: '产品', dataIndex: 'productName', // render: renderContent, }, { title: '设备在线', // colSpan: 2, dataIndex: 'online', render: (text: any) => text || 0, // render: (value, row, index) => { // const obj = { // children: value, // props: { // // rowSpan: 0, // }, // }; // if (index === 2) { // obj.props.rowSpan = 2; // } // // These two are merged into above cell // if (index === 3) { // obj.props.rowSpan = 0; // } // if (index === 4) { // obj.props.colSpan = 0; // } // return obj; // }, }, { title: '设备离线', // colSpan: 0, dataIndex: 'offline', render: (text: any) => text || 0, }, { dataIndex: 'alarmCount', title: '告警记录', render: (text: any) => text || 0, }, ]; return ( <Spin spinning={spinning}> <Card bordered={false}> <div className={styles.tableList}> <div className={styles.tableListForm}> {/* <Search search={(params: any) => { setSpinning(true); params.state = searchParam.terms?.state; handleSearch({ terms: params, pageSize: 10, sorts: searchParam.sorts }); }} /> */} </div> <div className={styles.StandardTable} style={{ marginTop: 10 }}> {/* <Table size='middle' columns={columns} dataSource={(deviceData || {}).data} rowKey="id" onChange={onTableChange} pagination={{ current: deviceData.pageIndex + 1, total: deviceData.total, pageSize: deviceData.pageSize, }} /> */} <Table size="small" pagination={false} columns={tenantAdmin ? columns2 : columns2.filter(i => i.dataIndex !== 'name')} dataSource={data} bordered /> </div> </div> </Card> </Spin> ); }
Example #11
Source File: index.origin.ts From angular-miniprogram with MIT License | 4 votes |
/**
* @experimental Direct usage of this function is considered experimental.
*/
export function execute(
options: KarmaBuilderOptions,
context: BuilderContext,
transforms: {
webpackConfiguration?: ExecutionTransformer<Configuration>;
// The karma options transform cannot be async without a refactor of the builder implementation
karmaOptions?: (options: KarmaConfigOptions) => KarmaConfigOptions;
} = {}
): Observable<BuilderOutput> {
// Check Angular version.
assertCompatibleAngularVersion(context.workspaceRoot);
let singleRun: boolean | undefined;
if (options.watch !== undefined) {
singleRun = !options.watch;
}
return from(
initialize(options, context, transforms.webpackConfiguration)
).pipe(
switchMap(async ([karma, webpackConfig]) => {
const karmaOptions: KarmaConfigOptions = {
singleRun,
};
// Convert browsers from a string to an array
if (options.browsers) {
karmaOptions.browsers = options.browsers.split(',');
}
if (options.reporters) {
// Split along commas to make it more natural, and remove empty strings.
const reporters = options.reporters
.reduce<string[]>((acc, curr) => acc.concat(curr.split(',')), [])
.filter((x) => !!x);
if (reporters.length > 0) {
karmaOptions.reporters = reporters;
}
}
// prepend special webpack loader that will transform test.ts
if (options.include && options.include.length > 0) {
const mainFilePath = getSystemPath(
join(normalize(context.workspaceRoot), options.main)
);
const files = findTests(
options.include,
dirname(mainFilePath),
context.workspaceRoot
);
// early exit, no reason to start karma
if (!files.length) {
throw new Error(
`Specified patterns: "${options.include.join(
', '
)}" did not match any spec files.`
);
}
// Get the rules and ensure the Webpack configuration is setup properly
const rules = webpackConfig.module?.rules || [];
if (!webpackConfig.module) {
webpackConfig.module = { rules };
} else if (!webpackConfig.module.rules) {
webpackConfig.module.rules = rules;
}
rules.unshift({
test: mainFilePath,
use: {
// cannot be a simple path as it differs between environments
loader: SingleTestTransformLoader,
options: {
files,
logger: context.logger,
},
},
});
}
karmaOptions.buildWebpack = {
options,
webpackConfig,
logger: context.logger,
};
const config = await karma.config.parseConfig(
resolve(context.workspaceRoot, options.karmaConfig),
transforms.karmaOptions
? transforms.karmaOptions(karmaOptions)
: karmaOptions,
{ promiseConfig: true, throwErrors: true }
);
return [karma, config] as [typeof karma, KarmaConfigOptions];
}),
switchMap(
([karma, karmaConfig]) =>
new Observable<BuilderOutput>((subscriber) => {
// Pass onto Karma to emit BuildEvents.
karmaConfig.buildWebpack ??= {};
if (typeof karmaConfig.buildWebpack === 'object') {
(karmaConfig.buildWebpack as any).failureCb ??= () =>
subscriber.next({ success: false });
(karmaConfig.buildWebpack as any).successCb ??= () =>
subscriber.next({ success: true });
(karmaConfig.buildWebpack as any).testContext = (
context as any
).testContext;
}
// Complete the observable once the Karma server returns.
const karmaServer = new karma.Server(
karmaConfig as Config,
(exitCode) => {
subscriber.next({ success: exitCode === 0 });
subscriber.complete();
}
);
const karmaStart = karmaServer.start();
// Cleanup, signal Karma to exit.
return () => karmaStart.then(() => karmaServer.stop());
})
),
defaultIfEmpty({ success: false })
);
}