A specialized wrapper for push notifications in Cordova that utilizes observables for streamlined

When working with the phonegap-plugin-push for cordova, you will come across various functions that use the following syntax:

function name(successCallback(),errorCallback(),options)

I am interested in creating a wrapper function that returns an Observable, but I'm facing some challenges when it comes to implementing it using typescript for angular2.

So, ideally, the code should resemble something like this:

name.subscribe((data)=>{...},(err)=>{})

Up until now, my experience has mostly involved subscribing to existing observables like http.

Therefore, the implementation should be similar to:

public unregister(options):Observable<any>{
  if(window.PushNotification){
    window.PushNotification.unregister(...)
  }
}

Any help in advance would be greatly appreciated!

Answer №1

To generate a fresh Observable, you have the option of using either create or constructing it directly.

//Function to link a cordova style method with a function that returns Observables
function bindCordovaCallback(fn) {
  //Creates and returns a new function 
  return (...opts) => 
    Rx.Observable.create(observer => {
      //Assuming only one call to success will be triggered
      const nextCallback = (v) => { observer.next(v); observer.complete(); }

      const errCallback = (e) => observer.error(e);

      //Calls the provided method.
      fn(nextCallback, errCallback, ...opts);

      //If needed, insert cancellation logic here
      return Subscription.EMPTY;
    });
}

const nameObservable = bindCordovaCallback(name)(opts);

//Every subscription triggers the underlying method just like $http in angular2
nameObservable.subscribe(data => {...}, err => {...}

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

I am attempting to store the primary array in local storage, but unfortunately, the value is not being saved within the React context API

I attempted to store the main array in local storage and retrieve it as global state, but I am facing an issue where the data is not being saved in the local storage. This file represents my context. import { createContext, useReducer, ReactNode, FC, use ...

Retrieve the information from the router link

I have a question regarding accessing the value passed through a routerlink in an anchor tag. How can I achieve this? https://i.stack.imgur.com/Qf500.png In the screenshot above, you can see that "bob" is the data being passed to the component when the a ...

Creating a JSON object from two arrays is a simple process

Consider the following two arrays: let values = ["52", "71", "3", "45", "20", "12", "634", "21"]; let names = ["apple", "orange", "strawberry", &q ...

The error message "TypeError [ERR_UNKNOWN_FILE_EXTENSION]: The file extension ".ts" is not recognized for the file located at /Project/src/index

Whenever I run npm run dev, I keep encountering the following error: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /Project/src/index.ts. Despite having all my settings configured as recommended, Here is a snippet of my package ...

Can a TypeScript interface inherit from multiple other interfaces simultaneously?

Hello Angular Community, I have a question regarding nesting three interfaces within another interface. Let me explain with some code: I am attempting to integrate the IProject1, IProject2, and IProject3 interfaces into the IAdmin2 interface: Thank you ...

Tips for handling mismatched function parameters in TypeScript when using an unspecified data type

Even though I wish it wasn't the case, TypeScript accepts the code below in strict mode. The function's value argument is defined as either an unknown or an any type, meaning it can be anything at this point as it is being passed along. However, ...

The angular component cannot be bound as it is not recognized as a valid property

In an attempt to conditionally assign a class based on the value of a boolean variable, I have declared the variable in the parent component: public alteredSidebar: boolean; This is my approach for dynamically setting the classname: <div [class ...

Extend the row of the table according to the drop-down menu choice

I am working on a feature where a dropdown menu controls the expansion of rows in a table. Depending on the option selected from the dropdown, different levels of items need to be displayed in the table. For example, selecting level 1 will expand the first ...

Lazy loading a child component in Angular 8: A step-by-step guide

In my project, I have a complex component that consists of multiple modals (NgbModal). These modals are connected to various child components. My goal is to implement lazy loading for these child components. Dashboard Module | |--> Dashboa ...

Common Errors in Angular 2 due to TSLint

I am encountering multiple errors in my code. I am using Angular 2 with TSLint: constructor(http: Http) { this.http = http; --> let currentUser = JSON.parse(localStorage.getItem("currentUser")); this.token = currentUser && currentUser.t ...

Choosing Between Absolute and Relative Paths for Angular Component's 'templateUrls'

Could anyone assist me with resolving the issue I'm facing with 1 vs 2? 1) In my Angular project, I have implemented AoT for production. This necessitated changing my source code to utilize templateUrl and styleUrls that are relative to the component ...

What steps can be taken to safeguard data while navigating within the Angular framework?

I am facing an issue with storing an array of items in a service (referred to as cart service) and displaying it in the component (cart.component.ts). The components bgview.component.ts and single.component.ts are involved in selecting individual items, wi ...

My function won't get called when utilizing Angular

My Angular code is attempting to hide columns of a table using the function shouldHideColumn(). Despite my efforts, I am unable to bind my tags to the <th> and <td> elements. An error keeps popping up saying Can't bind to 'printerColu ...

Tips for displaying field options after typing parentheses in TypeScript in Visual Studio Code

Whenever the letter "b" is typed, the suggestion of "bar" appears. However, I would prefer if the suggestions show up immediately after typing the brackets. https://i.stack.imgur.com/OFTO4.png ...

How to implement a timeout feature in JavaScript/TypeScript for cloud functions

I'm currently facing an issue with trying to delay certain actions using Cloud Firestore. Despite my attempts, the setTimeout/setInterval functions don't seem to be working as expected in my code. export const onTimerCreate = functions.firestore ...

Ways to generate an Angular 7 component

Seeking guidance on creating an angular 7 component. I have forked a jsFiddle at this link: https://jsfiddle.net/gauravshrestha/fdxsywLv/. The chart in the fiddle allows data points to be dragged up and down. My goal is to convert this into a component whe ...

Converting the 'require' call to an import may be a more efficient method when importing package.json in a typescript file

In my current project, I am creating a class where I am directly accessing the package version number like this: const pkg = require('../package.json') export class MyClass() { constructor() { // Set the base version from package.jso ...

Utilizing the date pipe in Angular2 to format multiple dates in an array

As a newcomer to front-end development and Angular2, I am faced with the task of creating an app that displays a date range based on given fromDate and endDate values. The date range format should be flexible, accommodating cases where months or years diff ...

Ensuring the accurate usage of key-value pairs in a returned object through type-checking

After generating a type definition for possible response bodies, I am looking to create a function that returns objects shaped as { code, body }, which are validated against the typing provided. My current solution looks like this: type Codes<Bodies> ...

Angular 10: Display a notification when all checkboxes have been ticked

I am currently working on a project that involves Angular 10. The initial requirement was as follows: Users are presented with a list from which they need to choose one option using radio buttons. For example: the user selects covid19 from the given lis ...