【发布时间】:2021-11-05 23:31:15
【问题描述】:
我正在尝试使用图片将项目添加到我的firestore中,因为base64图片大于2Mb,我正在使用firestore来存储图像并获取url来设置相应的字段。
为此,我将我的项目发送到 firebase,并带有一个空白字段作为图片,然后,我将图片发送到 firebase 存储。直到这里一切正常,但是当我尝试获取下载 url 并将其设置为我的项目时,它不起作用。
这是我的代码:
这是我的页面,我正在向 Firestore 添加新项目。
export class AddFoodPage implements OnInit {
...
addFood() {
this.setFood();
this.foodService.addFood(this.food, this.foodPicture.base64).then(() => {
this.presentAlert();
this.tagList = [];
this.ingredientList = [];
this.addFoodForm.reset();
});
}
...
private setFood() {
this.food = this.addFoodForm.value;
this.food.ingredientList = this.ingredientList;
this.food.specials = this.tagList;
this.foodPicture = this.imgService.getPicture();
this.food.photoUrl = '';
}
这里是我为该项目提供的服务:
export class FoodService {
private foodCollection: AngularFirestoreCollection<FoodView>;
constructor(
private afs: AngularFirestore,
private authService: AuthService,
private storage: AngularFireStorage
) {
this.foodCollection = this.afs.collection('food');
}
async addFood(food: FoodView, base64String: string) {
this.authService.getUserData().subscribe((_user) => {
food.cookerName = _user.displayName;
food.cookerId = _user.uid;
from(this.foodCollection.add(food)).subscribe((addedFood) =>
this.uploadFoodImage(base64String, addedFood.id, food.cookerId)
);
});
}
private uploadFoodImage(
base64String: string,
foodId: string,
userId: string
) {
const filePath = `foods/${userId}/${foodId}`;
const fileRef = this.storage.ref(filePath);
const task: AngularFireUploadTask = fileRef.putString(
base64String,
'base64',
{ contentType: 'image/png' }
);
return from(task).pipe(
switchMap(
(result) => {
return fileRef.getDownloadURL();
}
// Upload Task finished, get URL to the image
),
switchMap((photoUrl) => {
// Set the URL to the food document
const uploadPromise = this.afs
.doc(`food/${foodId}`)
.set(photoUrl, { merge: true });
console.log(photoUrl);
return from(uploadPromise);
})
);
}
在上面的代码中,switchMap函数中的代码没有执行,我不明白为什么,我错过了什么?图片已保存到 firebase 存储中,但文档未在 firestore 中更新。
这是我的食物模型:
export class FoodView {
fid: string;
cookerId: string;
cookerName: string;
title: string;
photoUrl: string;
ingredientList: string[] = [];
type: string;
hasAllergen: boolean;
specials: string[];
origin: string;
price: number;
quantity: number;
}
【问题讨论】:
标签: angular firebase ionic-framework google-cloud-firestore google-cloud-storage