我正在尝试创建服务以从Angular应用程序中的任何位置上传图像。
我的服务使用“ putstring”功能将base64图像上传到firebase,我想显示每次上传的进度。
在服务中,我可以访问“百分比变化” Obesrvable,但是我想从组件中访问此可观察值。问题是,一旦我将上传任务返回到组件,然后尝试访问该功能,它将不再起作用。看来我只能直接从服务而不是组件中访问此可观察的对象。
这无法做到这一点,因为我无法将此进度附加到GUI并向用户显示进度。
export class UploadService {
task: AngularFireUploadTask;
percentage : Observable<number>;
constructor(private firestoreService: FirestoreService,
private afStorage: AngularFireStorage) { }
async processBase64Image(uri: string, type: string, uid : string) {
try {
let data = await Filesystem.readFile({
path: uri
})
var metadata = { contentType: 'image/jpeg' };
const path = type + '/' + uid + `_${new Date().getTime()}.jpg`;
return this.afStorage.ref(path).putString(data.data, 'base64', metadata);
}
catch (error) {
console.log(error);
}
}
uploadBase64File(path: string, data: string, metadata? : any) {
console.log('Uploading To Firebase');
this.task = this.afStorage.ref(path).putString(data, 'base64', metadata);
this.percentage = this.task.percentageChanges();
return this.task;
//HERE I CAN EASILY ACCESS THE OBSERVABLE FUNCTION
}
我需要做的是从组件访问它:
@Component({
selector: 'app-add-skill',
templateUrl: './add-skill.page.html',
styleUrls: ['./add-skill.page.scss'],
})
export class AddSkillPage implements OnInit {
task: AngularFireUploadTask;
constructor(private userService: UserService,
private firestoreService: FirestoreService,
private uploadService: UploadService) { }
uploadSkill() {
this.uploadService.processBase64Image(this.photoUri, 'skills', this.user.uid)
.then((task) => {
task. <--- HERE I CANNOT ACCESS THE FUNCTION --- WHY?
console.log('image successfully uploaded');
})
.catch(error => {
console.log('IMAGE CAPTURE ERROR');
console.log(error);
this.showToast('There was an error uploading your image');
})
} }