Ionic2/angularJs2中的静态类 PhotoLibrary 调用不上

photoLibrary调用报错:No provider for PhotoLibrary;

在调用相册文件时有用到photolibrary,总有些莫名的报错,3月份的时候这个坑让我不知所措,现在写下来方便查看(也不知道Ionic2现在是否有变化),入坑过程:

按照官网示例:

1.添加插件:

cmd 到项目目录运行:

ionic plugin add cordova-plugin-photo-library --variable PHOTO_LIBRARY_USAGE_DESCRIPTION="To choose photos"


2. ts文件中添加:

import { PhotoLibrary } from '@ionic-native/photo-library';

constructor(private photoLibrary: PhotoLibrary) { }

  this.photoLibrary.requestAuthorization().then(() => {

    this.photoLibrary.getLibrary().subscribe({ next: library => {

    library.forEach(function(libraryItem) {

      console.log(libraryItem.id); // ID of the photo

       //........

  }); },

error: err => {}, complete: () => { console.log("could not get photos"); } }); })

.catch(err => console.log("permissions weren't granted"));

好,这一运行,就出现No provider for PhotoLibrary;

查了很久---------,终于发现了这个鬼;

在查看PhotoLibrary.java看到了一些静态的内部的类(没深入了解java---大概是这个意思):

public static XXX{}

而在java中的静态类 是不能使用继承的(使用 this、super关键字);

所以在.ts文件中就这样做-------->

import { PhotoLibrary } from '@ionic-native/photo-library';
constructor() { //1.构造函数中不注入PhotoLibrary
  
}
 theFunction(){
     //2.直接使用--不用this
  PhotoLibrary.requestAuthorization().then(() => {

    PhotoLibrary.getLibrary().subscribe({ next: library => {


    library.forEach(function(libraryItem) {

      console.log(libraryItem.id); // ID of the photo

       //........

  }); },

error: err => {}, complete: () => { console.log("could not get photos"); } }); })

.catch(err => console.log("permissions weren't granted"));
}
ionViewDidLoad(){
  //3.调用方法
  this.theFunction();
}
 

--------------最终调用成功了-------------------

总结:如果遇到类似的静态类,可以参照此方法。

 

posted @ 2017-04-26 21:21  babuge  阅读(707)  评论(0编辑  收藏  举报