Ionic2/angularJs2中的靜態類 PhotoLibrary 調用不上,ionic2angularjs2
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();
}
--------------最終調用成功了-------------------
總結:如果遇到類似的靜態類,可以參照此方法。