RXJS 6-承诺

时间:2018-10-31 09:56:57

标签: rxjs angular6 es6-promise angularfire2 rxjs6

我目前正在尝试将Observable转换为Promise。但是当我调用该方法时,什么也没有发生。我正在使用Angular 6。

服务

  public create(form: StoryForm): Promise<void | string> {
    const key: string = this.afStore.createId();

    return this.auth.authState.pipe(map(res =>
      <Story>{
        title: form.title, content: form.content, createdAt: new Date(), sid: key,
        uid: res.uid, username: res.displayName
      }
    )).toPromise().then((story: Story) =>
      this.afStore.doc(`stories/${key}`).set(story).catch(err => err.message));
  }

组件

  public save() {
    this.triedToSave = true;
    if (this.storyForm.valid) {
      this.storyService.create(this.storyForm.value)
        .then(() => this.router.navigate(['/stories']))
        .catch((err: string) => this.notify.danger(err));
    }
  }

保存应该做的是浏览或至少显示错误。

验证

如何实现authstate:它返回可观察到的一些用户信息。它是在其他服务中实现的,如下所示:

  public get authState(): Observable<firebase.User> {
    return this.afAuth.authState;
  }

编辑

让我感到困惑的是,如果我使用模拟对象却突然无法工作:

  public create(form: StoryForm) {
    const key: string = this.afStore.createId();

    return of({uid: 'blubb', displayName: 'kdsjf', photoUrl: 'kjdfkjfd'}).pipe(map(user => {
      return {
        title: form.title, content: form.content, createdAt: new Date(), sid: key,
        uid: user.uid, username: user.displayName, photoUrl: user.photoURL
      } as Story;
    })).toPromise();
  }

但是我想知道为什么toPromise在上面的示例中不起作用...

1 个答案:

答案 0 :(得分:1)

我猜测什么也没发生,因为当您触发save方法时,authState不会发出任何结果。显然,您希望authState observable或Subject总是会触发一些输出,只有在特定情况下才如此。

下面的代码创建一个-new- observable来侦听authState。

return this.auth.authState.pipe(map(res =>
      <Story>{
        title: form.title, content: form.content, createdAt: new Date(), sid: key,
        uid: res.uid, username: res.displayName
      }
    )).toPromise().then((story: Story) =>
      this.afStore.doc(`stories/${key}`).set(story).catch(err => err.message));

该代码仅由save方法触发。我的猜测是authState是可观察的或主题。您的代码仅在authState传递新值后才起作用-触发save方法之后。

使用模拟对象的代码可以工作,因为您创建了一个可观察的对象,该对象立即发出该值。

如果authState是主题,则将其替换为ReplaySubject(1)

如果它是可观察的,则需要像这样将其作为ReplaySubject发布:

authState.pipe(
    publishReplay(1),
    refCount()
);

要完全了解发生了什么,请阅读此文章: https://blog.mindorks.com/understanding-rxjava-subject-publish-replay-behavior-and-async-subject-224d663d452f

这是一篇Java文章,但适用相同的原理。

但是说实话,当我看到人们使用toPromise方法时,我感到畏缩:) 如果按预期使用rxjs,您会学得更快!

如果我要编写这段代码,它将看起来像这样:

public save$: Subject<StoryForm> = Subject<StoryForm>();
private destroy$: Subject<any> = new Subject();

ngOnDestroy(): void {
    this.destroy$.next();
}

onInit() {
    // the (click) eventhandler in your GUI should call save$.next(storyForm)
    // this will trigger this statement
    this.save$.pipe(
        // withLatestFrom will fetch the last value from an observable, 
        // it still needs to be a ReplaySubject or ReplaySubject for this to work though!
        // it will pass an array down the pipe with the storyForm value, and the last value from authState
        withLatestFrom(this.auth.authState),
        // switchMap does the actual work: note that we do not return a value, 
        // but an observable that should that return a value soon, that is why we need switchMap!
        switchMap(([storyForm, authInfo]) => {
            // i am assuming the "set" method returns an observable
            // if it returns a Promise, convert it using fromPromise
            return this.afStore.doc(`stories/${key}`).set(story).pipe(
                // catchError needs to be on your api call
                catchError(err => console.log(err))
            );
        }),
        // this will kill your subscriptino when the screen dies
        takeUntil(this.destroy$)
    ).subscribe(value => {
        // "value" will be the return value from the "set" call
        this.router.navigate(['/stories']);
    }
}