Anticipating a service that is dependent on multiple layers of promises and observables

My current project involves implementing the Ionic Native QR Scanner. Since I anticipate using the scanner across multiple modules, I decided to create a straightforward service that can launch the scanner and provide the result.

Initially, I am following the example code provided in the link above:

// within qrScannerService...
public scanQR(): Promise<void> {
    return this.qrScanner.prepare()
        .then((status: QRScannerStatus) => {
            if (status.authorized) {
                let scanSub = this.qrScanner.scan().subscribe((qrResult: string) => {

                    this.qrScanner.hide();
                    scanSub.unsubscribe();
                    // this is my ultimate goal.
                    return qrResult; 
                });
                this.qrScanner.show();
            } else if (status.denied) {
                console.log("denied");
            } else {
                // permission was denied, but not permanently.
            }
        })
        .catch((e: any) => console.log('Error is', e));
}

This is how I utilize the scanner service in my module:

private doQRScan() {
    this.qrScannerService.scanQR().then(result => {
        console.log(result);
    });      
}

In this set up, there is a promise chain doQRScan()->scanQR()->prepare()->scan(), which requires coordination between all three promises/observables. However, due to my limited experience with Angular, I am struggling to achieve this synchronization.

As it currently stands, prepare() fulfills its promise and doQRScan() completes without receiving the actual QR scan result.

Is there a solution or suggestion on how to tackle this issue?

Answer №1

To enhance your scanQR function, it is necessary to create a new promise. Although untested, the following code snippet can guide you:

public scanQR() {
return new Promise((resolve, reject) => {
    this.qrScanner.prepare()
        .then((status: QRScannerStatus) => {
            if (status.authorized) {
                let scanSub = this.qrScanner.scan().subscribe((qrResult: string) => {

                    this.qrScanner.hide();
                    scanSub.unsubscribe();
                    // The desired action.
                    // return qrResult;
                    resolve(qrResult) //-------> fulfilling the main promise
                });
                this.qrScanner.show();
            } else if (status.denied) {
                console.log("denied");
                reject("denied!")
            } else {
                // permission was denied temporarily.
                reject("denied!")
            }
        })
        .catch((e: any) =>
            console.log('Error is', e)
            reject(e)
        );
})

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Angular 7, Ngrx, and Rxjs 6 to efficiently share state data among lazily loaded modules

Currently, I am working with Angular 7 alongside Ngrx and Rxjs 6. In my project, I have two lazy loaded modules named A and B, each with its own selectors and reducers. The challenge I am facing is accessing the data stored in module B's state from m ...

Using ES6 modules with Node.js, Typescript, and the Winston library resulted in the error message: "error TS2307: Cannot find module 'winston'"

I've been attempting to make Winston work with node.js (v13.11.0) using ES6 modules and typescript, but unfortunately I haven't had any luck so far: My code resides in src/lib/logging.ts: import * as logger from 'winston'; // ... Init ...

Toggle switch with active state

I'm currently using Ionic 2 alongside Angular 2 beta 11. Is there a way to turn off the toggle switch? The Ionic documentation suggests using the checked attribute, but I've tried that and also attempted ng-checked with no luck. Any advice on t ...

The validation process in Redux forms

Imagine we have the following types defined: interface MyFormFields { FirstName: string; LastName: string; } type FieldsType = keyof MyFormFields; const field1: FieldsType = "c"; const field2 = "c" as FieldsType; Now, I am looking to implemen ...

Verifying TypeScript Class Instances with Node Module Type Checking

My current task involves converting our Vanilla JS node modules to TypeScript. I have rewritten them as classes, added new functionality, created a legacy wrapper, and set up the corresponding Webpack configuration. However, I am facing an issue with singl ...

Issue with accessing undefined property in Angular 2+ using Typescript

In my Angular 7 project, I am retrieving data from a service which looks like this: {name: "peter", datetime: 1557996975991} I have a method that is supposed to retrieve this data: myMethod() { this.myService.getdata().subscribe((res) = ...

Is there a substitute for useState in a Next.js server component?

With my static site at , the only interactive feature being the dark mode toggle, I understand that using useState is not feasible in a server component. export default function RootLayout({ children }: { children: React.ReactNode }) { const [darkMode, ...

Generating an instance of an enum using a string in Typescript

Having trouble accessing the enum members of a numeric enum in TypeScript using window[name]. The result is an undefined object. export enum MyEnum { MemberOne = 0, MemberTwo = 1 } export class ObjectUtils { public static GetEnumMembers(name ...

The Cordova Audio Plugin

I've been working on setting up the cordova-media-plugin, but I've run into an issue where the media files aren't playing. The logs are showing the following message: THREAD WARNING: ['Media'] took '22.759277' ms. Plugin ...

Can a webpage created with ASP.Net Core be encapsulated with Cordova?

My ASP.Net Core application utilizes server-side processing, particularly for cookie authentication, along with some Vue.js for added interaction. Can I package this code into mobile apps using Cordova, or will I need to refactor it to utilize XHR and JWT ...

Error: Jest + Typescript does not recognize the "describe" function

When setting up Jest with ts-jest, I encountered the error "ReferenceError: describe is not defined" during runtime. Check out this minimal example for more information: https://github.com/PFight/jest-ts-describe-not-defined-problem I'm not sure what ...

What is the best way to strip strings and special characters from a text, displaying only the numerical values without any commas, by

Using React Native TypeScript, I am looking to extract only the numbers from a string group without any commas. Is there a way to achieve this using regex match or replace? taskname = TASK_XC0.0.0.0.89t_abc_test let task = taskname.match( /[0-9]+/g, &apo ...

The functionality of arguments in the whenAllDone promise/deferred javascript helper seems to fail when attempting to encapsulate existing code within a Deferred

My goal is to implement the solution provided in TypeScript from Stack Overflow: UPDATE 2 - The issue with the original answer is that it does not support a single deferred. I have made modifications to reproduce the error in his fiddle. http://jsfiddle.n ...

Select one of 2 parameters and begin typing

I recently encountered a situation where I needed to define a type with an id field (string) and an oldId field (number), but I wanted these fields to be exclusive. For example: { id: "1234", name: "foo" } { oldId: 1234, name: "b ...

Can you explain the significance of the "@" symbol in the `import from '@/some/path'` statement?

When I use IntelliJ IDEA to develop a web application in TypeScript, the autocomplete feature suggests imports from other files within my project like this: import {Symbol} from '@/components/Symbol'; I am curious about the significance of the @ ...

Issue with React.js code not being detected in TSX file (Visual Studio 2015 Update 1 RC)

Currently, I am utilizing Visual Studio 2015 with update 1 release candidate. Interestingly, I have managed to successfully incorporate React.js code and syntax highlighting within a .JSX file. However, when it comes to a .TSX file, nothing seems to be wor ...

Unable to set up enzyme adapter

Currently, I am in the process of setting up the enzyme adapter for testing purposes. The code snippet that I have is quite straightforward: import * as enzyme from 'enzyme'; import * as Adapter from 'enzyme-adapter-react-16'; enzyme. ...

Display the initial x list items without utilizing ngFor in Angular 2

In the template, there are 9 <li> elements, each with a *ngIf condition present. It is possible that 5 or more of them may return true, but the requirement is to only display the first 4 or less if needed. Priority is given to the order of the < ...

Error encountered in Ionic iOS app: Custom Scheme URIs are restricted for 'WEB' client type

I'm utilizing this particular plugin. https://github.com/EddyVerbruggen/cordova-plugin-googleplus While the implementation is functioning well for Android, encountering issues with Google sign-in on iOS where it opens a Safari webview and throws a 4 ...

Saving data from a one-to-one relationship using TypeORM and NestJS in a socalled way is a breeze - here's how you

When working with TYPEORM, I have a requirement to create two entities in the database: one for the user and another to store tokens. However, I face a challenge when trying to fill both entities simultaneously during the user creation process. Can someone ...