Angular Маршрутизатор / распознаватель - Тип 'Наблюдаемый 'нельзя назначить типу' Observable <boolean>' - PullRequest
0 голосов
/ 29 апреля 2020

Я использую средство защиты маршрута (или распознаватель, я пытался использовать либо, но получил ту же ошибку), где я хочу получить Observable в качестве возвращаемого значения:

canActivate(): Observable<boolean> {
    return this.store.pipe(
      select(fromUserProfileState.getUserProfiles),
      tap((loaded: UserProfile[]) => {
        if (!loaded || loaded.length == 0) {
          this.store.dispatch(new fromUserProfileActions.LoadUPs());
        } else {
          return of(true);
        }
      }),
      filter((loaded: UserProfile[]) => loaded.length > 0),
      first()
    );
  }

Однако это не ' t возвращает Observable, он возвращает Observable, что недопустимо. Как настроить операторы rx js (v 6.5.5) так, чтобы они возвращали только наблюдаемые?

enter image description here

Ответы [ 3 ]

1 голос
/ 29 апреля 2020

Благодаря @julianobrasil это сработало для моего случая:

canActivate(): Observable<boolean> {
    return this.store.pipe(
      select(fromUserProfileState.getUserProfiles),
      // Convert the information from UserProfiles to a boolean
      // Thils will also be used to authorize the navigation
      map((loaded: UserProfile[]) => !!(loaded && loaded.length)),
      // dispatch an action is no user profile has been loaded
      tap((isLoaded: boolean) => {
        if (!isLoaded) {
          this.store.dispatch(new fromUserProfileActions.LoadUPs());
        }
      }),
      // wait till the array is populated
      filter((loaded) => loaded),
      // complete the observable
      take(1)
    );
  }

По сути, он ожидает заполнения массива UserProfile [].

1 голос
/ 29 апреля 2020

Попробуйте это:

canActivate(): Observable<boolean> {
  return this.store.pipe(
    select(fromUserProfileState.getUserProfiles),
    // Convert the information from UserProfiles to a boolean
    // Thils will also be used to authorize the navigation
    map((loaded: UserProfile[]) => !!(loaded && loaded.length)),
    // dispatch an action is no user profile has been loaded
    tap((isLoaded: Boolean) => {
      if (!isLoaded) {
        this.store.dispatch(new fromUserProfileActions.LoadUPs());
      }
    }),
    // complete the observable
    take(1)
  );
}
0 голосов
/ 29 апреля 2020

нажатие используется для побочных эффектов, но возвращает наблюдаемую информацию, идентичную наблюдаемой из источника.

first () не требуется, поскольку canActivate () откажется от подписки

Возможно, вы можете нарушить навигацию если только LoadUPs () не подготовит все данные и не выполнит навигацию как новый побочный эффект

canActivate(): Observable<boolean> {
    return this.store.pipe(
      select(fromUserProfileState.getUserProfiles),
      tap((loaded: UserProfile[]) => {
        if (!loaded || loaded.length == 0) {
          this.store.dispatch(new fromUserProfileActions.LoadUPs());
        }
      }),
      map((loaded: UserProfile[]) => {
        if (!loaded || loaded.length == 0) {
          return false;
        } else {
          return true;
        }
      })
    );
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...