我試圖在我的Firestore中添加一個帶有圖片的專案,因為base64圖片大于2Mb,我使用Firestore來存盤圖片,并獲得url來設定相應的欄位。
為了做到這一點,我把我的專案發送到Firebase,并為圖片設定了一個空欄位,然后,我把圖片發送到Firebase存盤。直到這里,一切都很好,但當我試圖得到下載的網址,并把它設定到我的專案,它不作業。
這里是我的代碼:
這是我的頁面,我在其中添加一個新的專案到Firestore。
export class AddFoodPage 實作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。
私有存盤。AngularFireStorage
) {
this.foodCollection = this。 afs.collection('food')。
}
async addFood(food: FoodView, base64String: string) {
this.authService.getUserData()。 subscribe((_user) =>/span> {
food.cookerName = _user.displayName。
food.cookerId = _user.uid;
from(this.foodCollection。 add(food)).subscribe((addedFood) =>/span>
this.uploadFoodImage(base64String, addedFood.id, food.cookerId)
);
});
}
private uploadFoodImage()
base64String: string,
foodId: string,
userId: 字串
) {
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()。
}
//上傳任務完成,獲得圖片的URL。
),
switchMap((photoUrl) => {
//設定食物檔案的URL。
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;
價格: 數字。
數量: 數值。
}
uj5u.com熱心網友回復:
你可以將Observables分為兩種不同的型別。"熱 "和 "冷 "觀察變數。對于熱觀察變數,你可以在觀察變數所代表的函式之外得到發射值的來源。 另一方面,冷觀察變數在它自己的函式中創建了源。因此,為了讓冷觀察變數發出任何值,主體必須至少運行一次。
在你的例子中,form(task)似乎創建了一個冷觀察變數。因此,為了首先創建資料源,你需要通過訂閱函式來呼叫它。
為了縮短時間。只要在你的管道后面添加一個.subscribe()即可。
return from(task).pipe(
switchMap(
(result) => {
return fileRef.getDownloadURL()。
}
//上傳任務完成,獲得圖片的URL。
),
switchMap((photoUrl) => {
//設定食物檔案的URL。
const uploadPromise = this.afs.
.doc(`food/${foodId}`)
.set(photoUrl, { merge: true })。)
console.log(photoUrl)。
return from(uploadPromise)。
})
).subscribe()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/319144.html
標籤:
