ionic2observableangular2-providers

Ionic 2: How to call Provider function in Controller class


I have created new Cordova Plugin only on my machine. Then I added it to my project. It is working fine when I call that plugin. Now, I tried to make a structured caller for my plugin. I created a Provider for it, but the problem is I don't know how to call my plugin function from my Controller class. Below is my sample code.

Provider: my-service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

declare let myPlugin: any;

@Injectable()
export class MyService {

  constructor(public http: Http) {
    console.log('Hello MyService Provider');
  }

  public myFunction() {
    myPlugin.myPluginFunction(
      (data) => {
        return data;
      },

      (err) => {
        return err;
      });
  }
}

Pages: my-page.ts

import { Component } from '@angular/core';
import { NavController, ViewController } from 'ionic-angular';

import { MyService } from '../../providers/my-service';

@Component({
  selector: 'page-my-page-ionic',
  templateUrl: 'hello-ionic.html'
})
export class MyPage {
  constructor(private viewCtrl: ViewController, private myService: MyService) {}

  ionViewWillEnter() {

    //I tried to call like this
    this.myService.myFunction().subscribe(
      data => {
        alert("success");
      },
      error => {
        alert("error");
      });
  }
}

It returns me this error - Property 'subscribe' does not exist on type 'void'. I don't know how to call that function, since my provider returns me success or error.


Solution

  • I think since your myFunction() does not return any observable you cannot subscribe to it. It just returns data directly.

    You can use it like this in this case:

    var data = this.myService.myFunction();
    console.log("Data from plugin is :", data);
    

    If you want to use it as an Observable, return a new observable like this:

    public myFunction() {
        return Observable.create(observer => {
            myPlugin.myPluginFunction(
            (data) => {
                observer.next(data);
            },
            (err) => {
                observer.next(data);
            });
        },
        (err) => {
            observer.error(err);
        });
    }