发布到Firebase数据库参考之前的Firebase存储下载URL

时间:2017-07-07 11:04:24

标签: angular typescript firebase firebase-storage angularfire2

使用firebase进行角度4项目。

我正在努力研究如何保证在运行下一步之前从Observable返回结果。

我知道你不能保证使用Observable,因为重点是它是一个数据流,因此我的困境。

我正在尝试将图片上传到firebase存储,在运行对firebase数据库的更新之前检索其下载URL

任何建议都将受到赞赏。

注册用户服务

$key: string;
    downloadUrl: string;
    currentUser: any;
    loginId: string;

    constructor(
        private db: AngularFireDatabase,
        private firebaseUploadService: FirebaseUploadService,
        private authService: AuthService) {
        this.firebaseUploadService.currentUrl.subscribe(url => this.downloadUrl = url);
    }

registerUser(firebaseRef: string, user: UserModel): Observable<any> {

        // Create a separate object for file upload with the file passed via the entity
        const file = Object.assign(<UploadModel>{}, user.imagePath);
        user.$key = this.authService.currentUserId;

        return this.firebaseUploadService.pushUpload(user.$key, file).switchMap(upload => {
            console.log('upload returned from service: ', upload)
            user.imagePath = this.downloadUrl;
            return Observable.fromPromise(this.db.object(firebaseRef + '/' + user.$key).update(user));
        });
    }

Firebase上传服务

    currentUser: any;
    uploads: FirebaseListObservable<UploadModel[]>;

    private urlSource = new BehaviorSubject('http://saveabandonedbabies.org/wp-content/uploads/2015/08/default.png');
    currentUrl = this.urlSource.asObservable();

    constructor() {
    }

pushUpload(firebaseRef: string, upload: UploadModel): any {

        const storageRef = firebase.storage().ref();
        const uploadTask = storageRef.child(`${firebaseRef}/${upload.file.name}`).put(upload.file);

        uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
            (snapshot) => {
                // upload in progress
                upload.progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
            },
            (error) => {
                // upload failed
                console.log(error)
            },
            () => {
                // upload success
                upload.url = uploadTask.snapshot.downloadURL
                this.urlSource.next(upload.url)
                upload.name = upload.file.name
            }
        );
        return this.urlSource;
    }

0 个答案:

没有答案