2017-02-17 21 views
0

我只在我的機器上創建了新的Cordova插件。然後我將它添加到我的項目中。當我調用該插件時它工作正常。現在,我試圖爲我的插件創建一個結構化的調用者。我爲它創建了一個提供程序,但問題是我不知道如何從我的Controller類調用我的插件函數。以下是我的示例代碼。Ionic 2:如何在控制器類中調用提供者函數

提供者:我-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; 
     }); 
    } 
} 

頁數:我-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"); 
     }); 
    } 
} 

它返回我這個錯誤 - Property 'subscribe' does not exist on type 'void'.我不知道該怎麼調用該函數,因爲我的提供程序返回我successerror

回答

1

我想因爲你的myFunction()沒有返回任何可觀察的,你不能訂閱它。它只是直接返回數據。

您可以使用它像這樣在這種情況下:

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

如果你想使用它作爲一個觀察的,返回一個新的觀察到的是這樣的:

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

謝謝你,它的工作: )。所以現在我知道如何使用Observable。 –

+0

很高興幫助。 :) –

相關問題