rxjs/operators#flatMap TypeScript Examples

The following examples show how to use rxjs/operators#flatMap. 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: user-detail.component.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
ngOnInit() {
    this.isComponentAlive = true;
    this.route.paramMap
      .pipe(
        takeWhile(() => !!this.isComponentAlive),
        flatMap((params) => {
          this.user = null;
          const userId = params.get('uuid');
          return this.userService.getUser(userId).pipe(
            flatMap((user: IUser) => {
              this.user = user;
              return this.userService.getSimilarUsers(userId);
            })
          );
        })
      )
      .subscribe((similarUsers: IUser[]) => {
        this.similarUsers = similarUsers;
      });
  }
Example #2
Source File: wallet.service.ts    From StraxUI with MIT License 6 votes vote down vote up
private buildAndSendInterFluxTransaction(transaction: InterFluxTransaction): Observable<InterFluxTransactionResponse> {
    const observable = this.post<BuildTransactionResponse>('wallet/build-interflux-transaction', transaction);

    return observable.pipe(

      map(response => {
        response.isSideChain = transaction.isSideChainTransaction;
        return response;
      }),

      flatMap((buildTransactionResponse) => {
        return this.post('wallet/send-transaction', new TransactionSending(buildTransactionResponse.hex)).pipe(
          map(() => {
            return new InterFluxTransactionResponse(transaction, buildTransactionResponse.fee, buildTransactionResponse.isSideChain);
          }),
          tap(() => {
            this.refreshWallet();
          })
        );
      }),

      catchError(err => this.handleHttpError(err))
    );
  }
Example #3
Source File: wallet.service.ts    From StraxUI with MIT License 6 votes vote down vote up
private buildAndSendTransaction(transaction: Transaction | OpreturnTransaction): Observable<TransactionResponse> {
    const observable = this.post<BuildTransactionResponse>('wallet/build-transaction', transaction);

    return observable.pipe(
      map(response => {
        response.isSideChain = transaction.isSideChainTransaction;
        return response;
      }),
      flatMap((buildTransactionResponse) => {
        return this.post('wallet/send-transaction', new TransactionSending(buildTransactionResponse.hex)).pipe(
          map(() => {
            return new TransactionResponse(transaction, buildTransactionResponse.fee, buildTransactionResponse.isSideChain);
          }),
          tap(() => {
            this.refreshWallet();
          })
        );
      }),
      catchError(err => this.handleHttpError(err))
    );
  }
Example #4
Source File: authentication.service.ts    From sba-angular with MIT License 6 votes vote down vote up
/**
     * Initiate authentication using the ng2-ui-auth library. The authentication process will be performed
     * in a browser popup window
     *
     * @param provider The name of the provider to use. This is the name configured in the Sinequa administration
     * console
     */
    authenticateWithProvider(provider: string): Observable<any> {
        // AuthService.authenticate opens a popup. On some platforms (Firefox) this is asynchronous
        // so we add a delay (timer(0)) so the caller can create a promise from the returned observable
        // without yielding
        const observable = timer(0).pipe(flatMap((value) => {
            const observable1 = this.authService.authenticate(provider, true).pipe(share());
            Utils.subscribe(observable1,
                (response) => {
                    // NB response should be the return value from JOAuth/JSaml json methods
                    // It can be undefined eg if the popup fails to open
                    if (response) {
                        this.processedCredentials = {
                            kind: LEGACY_PROCESSED_CREDENTIALS_KIND,
                            data: {
                                csrfToken: response.csrfToken,
                                provider
                            }
                        };
                    }
                });
            return observable1;
        }));
        return observable;
    }
Example #5
Source File: authentication-popup.service.ts    From sba-angular with MIT License 6 votes vote down vote up
open(url: string, options: any/*IOauth2Options | IOauth1Options*/, cordova: boolean | undefined): Observable<Window> {
        if (Utils.startsWith(url, this.startConfig.apiPath!)) {
            return this.httpClient.get<{redirectUrl: string}>(url, {
                params: Utils.makeHttpParams({
                    noUserOverride: true,
                    noAutoAuthentication: true,
                    tokenInCookie: true,
                    loginInPopup: true
                })
            }).pipe(flatMap((ret) => {
                return super.open(ret.redirectUrl, options, cordova);
            }));
        }
        return super.open(url, options, cordova);
    }
Example #6
Source File: authentication-oauth.service.ts    From sba-angular with MIT License 6 votes vote down vote up
authenticate<T extends object | string>(name: string, userData: any): Observable<T> {
        const options = this.configService.options.providers[name];
        if (options.sqInitState) {
            return this.httpClient.get<{state: string}>(Utils.addUrl(this.startConfig.apiPath!, "oauth"), {
                params: Utils.makeHttpParams({
                    action: "initstate",
                    provider: options.name,
                    tokenInCookie: true,
                    loginInPopup: true,
                    noUserOverride: true,
                    noAutoAuthentication: true
                })
            }).pipe<T>(flatMap<{state: string}, Observable<T>>((ret) => {
                options.state = ret.state;
                return super.authenticate(name, userData);
            }));
        }
        return super.authenticate(name, userData);
    }
Example #7
Source File: suggest.service.ts    From sba-angular with MIT License 6 votes vote down vote up
get(suggestQuery: string, text: string, fields?: string | string[], query?: Query): Observable<Suggestion[]> {
        if (!this.appService.ccquery) {
            return of([]);
        }
        const observable = this.suggestQueryWebService.get(suggestQuery, text, this.appService.ccquery.name, fields);
        return observable.pipe(
            flatMap(suggests => {
                if (!fields) {
                    if (!suggests) {
                        suggests = [];
                    }
                    this.addFields(text, suggests);
                }
                else {
                    if (!suggests || suggests.length === 0) {
                        const _fields = Utils.isArray(fields) ? fields : [fields];
                        fields = [];
                        for (const field of _fields) {
                            const column = this.appService.getColumn(field);
                            if (!!column && (column.eType === EngineType.csv || AppService.isScalar(column))) {
                                fields.push(field);
                            }
                        }
                        if (fields.length > 0) {
                            return this.suggestFieldWebService.get(text, fields, query).pipe(
                                map((suggests) => {
                                    suggests.forEach(value => value.display = Utils.toSqlValue(value.display)); // because dates get automatically converted by the interceptor
                                    return suggests;
                                }));
                        }
                    }
                }
                return of(suggests);
            }));
    }
Example #8
Source File: customer.detail.component.ts    From digital-bank-ui with Mozilla Public License 2.0 6 votes vote down vote up
ngOnInit(): void {
    this.customerSubscription$ = this.store
      .select(fromCustomers.getSelectedCustomer)
      .pipe(
        filter(customer => !!customer),
        tap(customer => (this.customer = customer)),
        tap(customer => (this.isCustomerActive = customer.currentState === 'ACTIVE')),
        flatMap(customer => this.customerService.getPortrait(customer.identifier)),
      )
      .subscribe(portrait => this.setBlob(portrait));

    this.catalog$ = this.store.select(fromCustomers.getCustomerCatalog);
  }
Example #9
Source File: bonus-card-detail.component.ts    From wingsearch with GNU General Public License v3.0 6 votes vote down vote up
initBonuses() {
    this.bonusCards$ = this.store.pipe(
      select(({ app }) => app.birdCards),
      first(),
      tap(birds => {
        this.birds = birds
        this.compatibleBirdIds = birds.filter((bird) => bonusSearchMap[this.data.card.id](bird)).map(bird => bird.id)
      }),
      flatMap(() => this.store.select(({ app }) => app.bonusCards)),
      map(cards => cards.filter(card => card['VP Average'] && card.id !== this.data.card.id)
        .map(bonus => ({
          ...bonus,
          birdIds: this.birds.filter((bird) => bonusSearchMap[bonus.id](bird))
            .map(bird => bird.id).filter(id => this.compatibleBirdIds.includes(id))
        }))
        .filter(bonus => bonus.birdIds.length).
        sort((a, b) => b.birdIds.length * b['VP Average'] - a.birdIds.length * a['VP Average'])
      )
    )
    this.cardWrapper?.nativeElement.scroll(0, 0)
    this.carousel?.nativeElement.scroll(0, 0)
  }
Example #10
Source File: service.ts    From jetlinks-ui-antd with MIT License 6 votes vote down vote up
public propertiesRealTime = (data: any) =>
    defer(() =>
      from(
        request(`/jetlinks/dashboard/_multi`, {
          method: 'POST',
          data,
        }),
      ).pipe(
        filter(resp => resp.status === 200),
        map(resp => resp.result),
        flatMap((data: Data[]) => from(data)),
        map(item => ({
          timeString: item.data.timeString,
          timestamp: item.data.timestamp,
          ...item.data.value,
        })),
      ),
    );
Example #11
Source File: service.ts    From jetlinks-ui-antd with MIT License 6 votes vote down vote up
public propertiesRealTime = (data: any) =>
    defer(() =>
      from(
        request(`/jetlinks/dashboard/_multi`, {
          method: 'POST',
          data,
        }),
      ).pipe(
        filter(resp => resp.status === 200),
        map(resp => resp.result),
        flatMap((data: Data[]) => from(data)),
        map(item => ({
          timeString: item.data.timeString,
          timestamp: item.data.timestamp,
          ...item.data.value,
        })),
      ),
    );
Example #12
Source File: products.service.ts    From nativescript-in-app-purchase with Apache License 2.0 6 votes vote down vote up
loadingProductItems(selectedProductType: InAppPurchaseType, inAppPurchaseStateUpdateListener: InAppPurchaseStateUpdateListener): Observable<ProductItem[]> {
        console.log('loadingProductItems(...)', selectedProductType)
        return this.loadProductIDs()
            .pipe(map(productIds => productIds))
            .pipe(flatMap(productIds => this.loadingProductsByProductIds(productIds, selectedProductType, inAppPurchaseStateUpdateListener),
                (productIds, result) => {
                    if (!result.success) {
                        throw result
                    }
                    const products = result.products
                    const productItems: ProductItem[] = []
                    for (const inAppProduct of products) {
                        productItems.push({
                            id: inAppProduct.productId,
                            product: inAppProduct,
                            options: productIds[inAppProduct.productId]
                        })
                    }
                    return productItems
                }
            ))
    }
Example #13
Source File: user-detail.component.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
ngOnInit() {
    this.isComponentAlive = true;
    this.route.paramMap
      .pipe(
        takeWhile(() => !!this.isComponentAlive),
        flatMap((params) => {
          this.user = null;
          console.log('params', params);
          this.similarUsers = null;
          const userId = params.get('uuid');
          return this.userService.getUser(userId).pipe(
            flatMap((user: IUser) => {
              this.user = user;
              return this.userService.getSimilarUsers(userId);
            })
          );
        })
      )
      .subscribe((similarUsers: IUser[]) => {
        this.similarUsers = similarUsers;
      });
  }
Example #14
Source File: user-detail.component.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
ngOnInit() {
    this.isComponentAlive = true;
    this.route.paramMap.pipe(
      takeWhile(() => !!this.isComponentAlive),
      flatMap(params => {
        this.user = null;
        this.similarUsers = null;
        const userId = params.get('uuid');
        return this.userService.getUser(userId)
          .pipe(
            flatMap((user: IUser) => {
              this.user = user;
              return this.userService.getSimilarUsers(userId);
            })
          );
      })
    ).subscribe((similarUsers: IUser[]) => {
      this.similarUsers = similarUsers;
    })
  }
Example #15
Source File: service.ts    From jetlinks-ui-antd with MIT License 5 votes vote down vote up
public permission = {
        query: (params: any) => defer(() => from(
            request(`/jetlinks/permission/_query/no-paging?paging=false`, {
                method: 'GET',
                params
            })).pipe(
                filter(resp => resp.status === 200),
                map(resp => resp.result as any[]),
                flatMap(data => of(...data)),
                filter((data: any) => (data.properties?.type || []).includes('api')),
                map(item => ({
                    title: item.name,
                    key: item.id,
                    children: item.actions.map((child: any) => ({
                        title: child.name,
                        key: child.action,
                    }))
                })),
                toArray()
            )),
        auth: (params: any) => defer(() => from(
            request(`/jetlinks/autz-setting/_query/no-paging?paging=false`, {
                method: 'GET',
                params
            })).pipe(
                filter(resp => resp.status === 200),
                map(resp => resp.result),
                flatMap(data => of(...data)),
                map(item => ({
                    key: item.permission,
                    actions: item.actions
                })),
                toArray(),
            )),
        save: (data: any) => defer(() => from(
            request(`/jetlinks/autz-setting/detail/_save`, {
                method: 'POST',
                data
            })).pipe(
                filter(resp => resp.status === 200),
            ))
    }
Example #16
Source File: products.service.ts    From nativescript-in-app-purchase with Apache License 2.0 5 votes vote down vote up
restoreProducts(inAppPurchaseStateUpdateListener: InAppPurchaseStateUpdateListener): Observable<InAppOrderHistoryResult> {
        return from(InAppPurchaseManager.bootStrapInstance(inAppPurchaseStateUpdateListener))
            .pipe(flatMap(purchaseManager => from(purchaseManager.purchaseHistory())))
    }
Example #17
Source File: products.service.ts    From nativescript-in-app-purchase with Apache License 2.0 5 votes vote down vote up
orderProduct(productItem: ProductItem, inAppPurchaseStateUpdateListener: InAppPurchaseStateUpdateListener): Observable<InAppOrderResult> {
        return from(InAppPurchaseManager.bootStrapInstance(inAppPurchaseStateUpdateListener))
            .pipe(flatMap(purchaseManager => from(purchaseManager.order(productItem.product))))
    }
Example #18
Source File: Status.tsx    From jetlinks-ui-antd with MIT License 4 votes vote down vote up
Status: React.FC<Props> = props => {
    const { device } = props;
    const metadata = JSON.parse(device.metadata);
    // const events = metadata.events
    //     .map((item: any) => {
    //         item.listener = [];
    //         item.subscribe = (callback: Function) => {
    //             item.listener.push(callback)
    //         }
    //         item.next = (data: any) => {
    //             item.listener.forEach((element: any) => {
    //                 element(data);
    //             });
    //         }
    //         return item;
    //     });
    const [properties, setProperties] = useState<any[]>(metadata.properties
        .map((item: any) => {
            item.listener = [];
            item.subscribe = (callback: Function) => {
                item.listener.push(callback)
            }
            item.next = (data: any) => {
                item.listener.forEach((element: any) => {
                    element(data);
                });
            }
            return item;
        }));

    const [loading, setLoading] = useState<boolean>(false);
    const propertiesWs: Observable<any> = getWebsocket(
        `instance-info-property-${device.id}-${device.productId}`,
        `/dashboard/device/${device.productId}/properties/realTime`,
        {
            deviceId: device.id,
            history: 0,
        },
    ).pipe(
        map(result => result.payload)
    );

    // const eventsWs: Observable<any> = getWebsocket(
    //     `instance-info-event-${device.id}-${device.productId}`,
    //     `/dashboard/device/${device.productId}/events/realTime`,
    //     {
    //         deviceId: device.id,
    //     },
    // ).pipe(
    //     map(result => result.payload)
    // );

    let propertiesMap = {};
    properties.forEach(item => propertiesMap[item.id] = item);
    // let eventsMap = {};
    // events.forEach((item: any) => eventsMap[item.id] = item);

    const [index, setIndex] = useState<number>(20);
    useEffect(() => {

        const properties$ = propertiesWs.subscribe((resp) => {
            const property = resp.value.property;
            const item = propertiesMap[property];
            if (item) {
                item.next(resp);
            }
        });

        // const events$ = eventsWs.subscribe((resp) => {
        //     const event = resp.value.event;
        //     const item = eventsMap[event];
        //     if (item) {
        //         item.next(resp);
        //     }
        // });

        return () => {
            properties$.unsubscribe();
            // events$.unsubscribe()
        };

    }, []);


    const renderProperties = useCallback(
        () => {
            const propertyCard = properties.map((item: any) => (
                <Col {...topColResponsiveProps} key={item.id}>
                    <PropertiesCard
                        item={item}
                        key={item.id}
                        device={device}
                        deviceId={props.deviceId}
                    />
                </Col>
            ))
            // const eventCard = events.map((item: any) => (
            //     <Col {...topColResponsiveProps} key={item.id}>
            //         <EventCard item={item} device={device} key={item.id} />
            //     </Col>
            // ));
            return [...propertyCard].splice(0, index)
        }, [device, index]);

    const service = new Service();

    useEffect(() => {
        const list = [{
            'dashboard': 'device',
            'object': device.productId,
            'measurement': 'properties',
            'dimension': 'history',
            'params': {
                'deviceId': device.id,
                'history': 15,
            },
        }];

        service.propertiesRealTime(list).pipe(
            groupBy((group$: any) => group$.property),
            flatMap(group => group.pipe(toArray())),
            map(arr => ({
                list: arr.sort((a, b) => a.timestamp - b.timestamp),
                property: arr[0].property
            }))
        ).subscribe((data) => {
            const index = properties.findIndex(item => item.id === data.property);
            if (index > -1) {
                properties[index].list = data.list;
            }
        }, () => {
            message.error('错误处理');
        }, () => {
            setLoading(true);
            setProperties(properties);
        })
    }, []);

    window.onscroll = () => {
        var a = document.documentElement.scrollTop;
        var c = document.documentElement.scrollHeight;

        var b = document.body.clientHeight;
        if (a + b >= c - 50) {
            setIndex(index + 10);
        }
    }

    return (
        <Spin spinning={!loading}>
            <Row gutter={24} id="device-instance-status" >
                <Col {...topColResponsiveProps}>
                    <DeviceState
                        refresh={() => { props.refresh() }}
                        state={device.state}
                        runInfo={device}
                    />
                </Col>

                {loading && renderProperties()}
            </Row>
        </Spin>
    )
}
Example #19
Source File: status.tsx    From jetlinks-ui-antd with MIT License 4 votes vote down vote up
Status: React.FC<Props> = props => {
    const { device, edgeTag } = props;
    const metadata = JSON.parse(device.metadata);
    
    const [properties, setProperties] = useState<any[]>(metadata.properties
        .map((item: any) => {
            item.listener = [];
            item.subscribe = (callback: Function) => {
                item.listener.push(callback)
            }
            item.next = (data: any) => {
                item.listener.forEach((element: any) => {
                    element(data);
                });
            }
            return item;
        }));
    const [loading, setLoading] = useState<boolean>(false);

    const propertiesWs: Observable<any> = getWebsocket(
        `instance-info-property-${device.id}-${device.productId}`,
        `/dashboard/device/${device.productId}/properties/realTime`,
        {
            deviceId: device.id,
            history: 0,
        },
    ).pipe(
        map(result => result.payload)
    );

    const propertiesEdge: Observable<any> = getWebSocket(
        `instance-info-property-${device.id}-${device.productId}`,
        `/edge-gateway-state/device/${device.productId}/properties/realTime`,
        {
            deviceId: device.id,
            history: 0,
        },
    ).pipe(
        map(result => result.payload)
    );

    let propertiesMap = {};
    properties.forEach(item => propertiesMap[item.id] = item);

    const [index, setIndex] = useState<number>(20);

    useEffect(() => {
        let properties$: Subscription | null = null;

        if (edgeTag) {
            properties$ = propertiesEdge.subscribe((resp) => {
                const property = resp.value.property;
                const item = propertiesMap[property];
                if (item) {
                    item.next(resp);
                }
            });
        } else {
            properties$ = propertiesWs.subscribe((resp) => {
                const property = resp.value.property;
                const item = propertiesMap[property];
                if (item) {
                    item.next(resp);
                }
            });
        }
        return () => {
            properties$ && properties$.unsubscribe();
        };
    }, []);


    const renderProperties = useCallback(
        () => {
            const propertyCard = properties.map((item: any) => (
                <Col {...topColResponsiveProps} key={item.id}>
                    <PropertiesCard
                        item={item}
                        key={item.id}
                        device={device}
                    />
                </Col>
            ))
            return [...propertyCard].splice(0, index)
        }, [device, index]);

    const service = new Service();

    useEffect(() => {
        const list = [{
            'dashboard': 'device',
            'object': device.productId,
            'measurement': 'properties',
            'dimension': 'history',
            'params': {
                'deviceId': device.id,
                'history': 15,
            },
        }];

        service.propertiesRealTime(list).pipe(
            groupBy((group$: any) => group$.property),
            flatMap(group => group.pipe(toArray())),
            map(arr => ({
                list: arr.sort((a, b) => a.timestamp - b.timestamp),
                property: arr[0].property
            }))
        ).subscribe((data) => {
            const index = properties.findIndex(item => item.id === data.property);
            if (index > -1) {
                properties[index].list = data.list;
            }
        }, () => {
            message.error('错误处理');
        }, () => {
            setLoading(true);
            setProperties(properties);
        })
    }, []);

    // window.onscroll = () => {
    //     var a = document.documentElement.scrollTop;
    //     var c = document.documentElement.scrollHeight;

    //     var b = document.body.clientHeight;
    //     if (a + b >= c - 50) {
    //         setIndex(index + 10);
    //     }
    // }

    return (
        <Spin spinning={!loading}>
            <Row gutter={24} id="device-edge-status" >
                <Col {...topColResponsiveProps}>
                    <DeviceState
                        refresh={() => { props.refresh() }}
                        state={device.state}
                        runInfo={device}
                    />
                </Col>

                {loading && renderProperties()}
            </Row>
        </Spin>
    )
}
Example #20
Source File: service.ts    From jetlinks-ui-antd with MIT License 4 votes vote down vote up
public member = {
    query: (id: string, params: any) =>
      defer(() =>
        from(
          request(`/jetlinks/tenant/${id}/members/_query/no-paging?paging=false`, {
            method: 'GET',
            params,
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
    query2: (params: any) =>
      defer(() =>
        from(
          request(`/jetlinks/tenant/members/_query`, {
            method: 'GET',
            params,
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
    query3: (id: string, params: any) =>
      defer(() =>
        from(
          request(`/jetlinks/tenant/${id}/members/_query`, {
            method: 'GET',
            params,
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
    queryNoPaging: (params: any) =>
      defer(() =>
        from(
          request(`/jetlinks/tenant/members/_query/no-paging?paging=false`, {
            method: 'GET',
            params,
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          flatMap(resp => from(resp.result)),
        ),
      ),

    bind: (id: string, data: { name: string; userId: string; admin: boolean }[]) =>
      defer(() =>
        from(
          request(
            this.tenant1 === true
              ? `/jetlinks/tenant/members/_bind`
              : `/jetlinks/tenant/${id}/members/_bind`,
            {
              method: 'POST',
              data,
            },
          ),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
    unBind: (id: string, data: string[]) =>
      defer(() =>
        from(
          request(
            this.tenant1 === true
              ? `/jetlinks/tenant/members/_unbind`
              : `/jetlinks/tenant/${id}/members/_unbind`,
            {
              method: 'POST',
              data,
            },
          ),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
    create: (id: string, data: any) =>
      defer(() =>
        from(
          request(`/jetlinks/tenant/${id}/member`, {
            method: 'POST',
            data,
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
    userlist: (params: any) =>
      defer(() =>
        from(
          // request(`/jetlinks/user/_query/no-paging?paging=false`, {
          request(`/jetlinks/user/_query`, {
            method: 'GET',
            params,
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
  };
Example #21
Source File: service.ts    From jetlinks-ui-antd with MIT License 4 votes vote down vote up
public assets = {
    bind: (
      id: string,
      data: {
        userId: string;
        assetType: string;
        assetIdList: string[];
        allPermission: boolean;
      }[],
    ) =>
      defer(() =>
        from(
          request(
            this.tenant1 !== true
              ? `/jetlinks/tenant/${id}/assets/${data[0].assetType}/_bind`
              : `/jetlinks/tenant/assets/${data[0].assetType}/_bind`,
            {
              method: 'POST',
              data,
            },
          ),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp),
        ),
      ),
    unbind: (
      id: string,
      data: {
        userId?: string;
        assetType: string;
        assetIdList: string[];
      }[],
    ) =>
      defer(() =>
        from(
          request(
            this.tenant1 !== true
              ? `/jetlinks/tenant/${id}/assets/${data[0].assetType}/_unbind`
              : `/jetlinks/tenant/assets/${data[0].assetType}/_unbind`,
            {
              method: 'POST',
              data,
            },
          ),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
    device: (params: any) =>
      defer(() =>
        from(
          request(`/jetlinks/device/instance/_query`, {
            method: 'GET',
            params,
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
    deviceCount: (params: any) =>
      defer(() =>
        from(
          request(`/jetlinks/device/instance/_count`, {
            method: 'GET',
            params,
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
    product: (params: any) =>
      defer(() =>
        from(
          request(`/jetlinks/device-product/_query`, {
            method: 'GET',
            params,
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
    productNopaging: (params: any) =>
      defer(() =>
        from(
          request(`/jetlinks/device-product/_query/no-paging?paging=false`, {
            method: 'GET',
            params,
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          flatMap(resp => from(resp.result)),
        ),
      ),
    productCount: (params: any) =>
      defer(() =>
        from(
          request(`/jetlinks/device-product/_count`, {
            method: 'GET',
            params,
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
    instanceNopaging: (params: any) =>
      defer(() =>
        from(
          request(`/jetlinks/device-instance/_query/no-paging?paging=false`, {
            method: 'GET',
            params,
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          flatMap(resp => from(resp.result)),
        ),
      ),
    protocol: (params: any) =>
      defer(() =>
        from(
          request(`/jetlinks/protocol/_query`, {
            method: 'GET',
            params,
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
    protocolCount: (params: any) =>
      defer(() =>
        from(
          request(`/jetlinks/protocol/_count`, {
            method: 'GET',
            params,
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
    members: (tenantId: string, assetType: string, assetId: string) =>
      defer(() =>
        from(
          request(`/jetlinks/tenant/${tenantId}/asset/${assetType}/${assetId}/members`, {
            method: 'GET',
          }),
        ).pipe(
          filter(resp => resp.status === 200),
          map(resp => resp.result),
        ),
      ),
  };
Example #22
Source File: Status1.tsx    From jetlinks-ui-antd with MIT License 4 votes vote down vote up
Status: React.FC<Props> = props => {
    const { device } = props;
    const metadata = JSON.parse(device.metadata);
    const events = metadata.events
        .map((item: any) => {
            item.listener = [];
            item.subscribe = (callback: Function) => {
                item.listener.push(callback)
            }
            item.next = (data: any) => {
                item.listener.forEach((element: any) => {
                    element(data);
                });
            }
            return item;
        });
    const [properties, setProperties] = useState<any[]>(metadata.properties
        .map((item: any) => {
            item.listener = [];
            item.subscribe = (callback: Function) => {
                item.listener.push(callback)
            }
            item.next = (data: any) => {
                item.listener.forEach((element: any) => {
                    element(data);
                });
            }
            return item;
        }));

    const [loading, setLoading] = useState<boolean>(false);
    const propertiesWs: Observable<any> = getWebsocket(
        `instance-info-property-${device.id}-${device.productId}`,
        `/dashboard/device/${device.productId}/properties/realTime`,
        {
            deviceId: device.id,
            properties: [],
            history: 0,
        },
    ).pipe(
        map(result => result.payload)
    );

    const eventsWs: Observable<any> = getWebsocket(
        `instance-info-event-${device.id}-${device.productId}`,
        `/dashboard/device/${device.productId}/events/realTime`,
        {
            deviceId: device.id,
        },
    ).pipe(
        map(result => result.payload)
    );

    let propertiesMap = {};
    properties.forEach(item => propertiesMap[item.id] = item);
    let eventsMap = {};
    events.forEach((item: any) => eventsMap[item.id] = item);

    const [index, setIndex] = useState<number>(20);
    useEffect(() => {

        const properties$ = propertiesWs.subscribe((resp) => {
            const property = resp.value.property;
            const item = propertiesMap[property];
            if (item) {
                item.next(resp);
            }
        });

        const events$ = eventsWs.subscribe((resp) => {
            const event = resp.value.event;
            const item = eventsMap[event];
            if (item) {
                item.next(resp);
            }
        });

        return () => {
            properties$.unsubscribe();
            events$.unsubscribe()
        };

    }, []);


    const renderProperties = useCallback(
        () => {
            const propertyCard = properties.map((item: any) => (
                <Col {...topColResponsiveProps} key={item.id}>
                    <PropertiesCard
                        item={item}
                        key={item.id}
                        device={device}
                    />
                </Col>
            ))
            const eventCard = events.map((item: any) => (
                <Col {...topColResponsiveProps} key={item.id}>
                    <EventCard item={item} device={device} key={item.id} />
                </Col>
            ));
            return [...propertyCard, ...eventCard].splice(0, index)
        }, [device, index]);

    const service = new Service();

    useEffect(() => {
        const list = [{
            'dashboard': 'device',
            'object': device.productId,
            'measurement': 'properties',
            'dimension': 'history',
            'params': {
                'deviceId': device.id,
                'history': 15,
            },
        }];

        service.propertiesRealTime(list).pipe(
            groupBy((group$: any) => group$.property),
            flatMap(group => group.pipe(toArray())),
            map(arr => ({
                list: arr.sort((a, b) => a.timestamp - b.timestamp),
                property: arr[0].property
            }))
        ).subscribe((data) => {
            const index = properties.findIndex(item => item.id === data.property);
            if (index > -1) {
                properties[index].list = data.list;
            }
        }, () => {
            message.error('错误处理');
        }, () => {
            setLoading(true);
            setProperties(properties);
            console.log(properties)
        })
    }, []);

    window.onscroll = () => {
        var a = document.documentElement.scrollTop;
        var c = document.documentElement.scrollHeight;

        var b = document.body.clientHeight;
        if (a + b >= c - 50) {
            setIndex(index + 10);
        }
    }

    return (
        <Spin spinning={!loading}>
            <Row gutter={24} id="device-instance-status" >
                <Col {...topColResponsiveProps}>
                    <DeviceState
                        refresh={() => { props.refresh() }}
                        state={device.state}
                        runInfo={device}
                    />
                </Col>

                {loading && renderProperties()}
            </Row>
        </Spin>
    )
}
Example #23
Source File: index.tsx    From jetlinks-ui-antd with MIT License 4 votes vote down vote up
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 #24
Source File: login.service.ts    From sba-angular with MIT License 4 votes vote down vote up
/**
     * Initiate the user login process. The method attempts to retrieve
     * the [application configuration]{@link CCApp}, the
     * [logged in user]{@link Principal} and the [user settings]{@link UserSettings}.
     * If a user is not currently authenticated then authentication is performed using
     * the {@link AuthenticationService} - OAuth/SAML if configured on the Sinequa Server
     * or manual using a login modal dialog provided using the {@link MODAL_LOGIN} injection
     * token.
     */
    login(): Observable<LoginData> {
        const appName = this.appService.appName;
        if (!appName) {
            return throwError({error: "App not specified"});
        }
        let appNeeded: boolean;
        if (this.router) {
            const hash = window.location.hash.replace("#", "");
            const href = hash.split("?")[0];
            const params = new URLSearchParams(hash.split("?")[1]);
            const queryParams = {}
            params.forEach((v, k) => queryParams[k] = v);

            // Pick up any user override from the query string
            const overrideUser = queryParams["overrideUser"];
            const overrideDomain = queryParams["overrideDomain"];
            if (overrideUser) {
                this.authenticationService.userOverride = {
                    userName: overrideUser,
                    domain: overrideDomain
                };
                delete queryParams["overrideUser"];
                delete queryParams["overrideDomain"];
                const url = Utils.makeURL(href);
                this.router.navigate([url.pathname], {queryParams});
            }
        }

        interface ObservableLoginData {
            app: Observable<CCApp> | undefined;
            principal: Observable<Principal> | undefined;
            userSettings: Observable<UserSettings> | undefined;
        }

        const makeObservables = (): ObservableLoginData => {
            const observables: ObservableLoginData = {
                app: undefined,
                principal: undefined,
                userSettings: undefined
            };
            if (!this.appService.app || (appName && this.appService.app.name !== appName)) {
                appNeeded = true;
                observables.app = this.appService.init();
            }
            else {
                observables.app = of(this.appService.app);
            }
            let loadUserSettings = false;
            if (!this.principalService.principal) {
                loadUserSettings = true;
                observables.principal = this.principalService.load();
            }
            else {
                observables.principal = of(this.principalService.principal);
            }
            if (!this.userSettingsService.userSettings || loadUserSettings) {
                observables.userSettings = this.userSettingsService.load();
            }
            else {
                observables.userSettings = of(this.userSettingsService.userSettings);
            }
            return observables;
        };

        const observable = this.authenticationService.autoAuthenticate()
            .pipe(flatMap((success) => {
                const observables = makeObservables();
                return forkJoin<ObservableLoginData, keyof ObservableLoginData>(observables);
            }));
        Utils.subscribe(observable,
            (result) => {
                console.log("loginService.login ok: ", result);
                this.setComplete();
                if (appNeeded) {
                    this._events.next({type: "session-start"});
                }
            },
            (error) => {
                console.log("loginService.login failed: ", error);
                // proceed to logout to clean process
                this.logout();
                return throwError(error);
            });
        return observable;
    }