1

因此,我尝试关注 ngrx/example-app,并且堆放了路由器防护装置。我的警卫不起作用。

import 'rxjs/add/operator/take';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/let';
import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { Router, CanActivate, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { Action } from '@ngrx/store';

import * as fromRoot from '../reducers';
import * as playlists from '../actions/playlists';

@Injectable()
export class PlaylistsExistsGuard implements CanActivate {
constructor(
    private store: Store<fromRoot.AppState>,
    private router: Router
) {}

waitForCollectionToLoad(): Observable<boolean> {
    return this.store.select(fromRoot.getPlaylistsLoaded)
        .filter(loaded => loaded)
        .take(1);
}

hasPlaylistsInStore(): Observable<boolean> {
    return this.store.select(fromRoot.getPlaylists)
        .map(playlists => !!playlists)
        .take(1);
}

getPlaylistsFromApi(): Observable<boolean> {
    this.store.dispatch(new playlists.GetPlaylistsAction());
    return this.store.select(fromRoot.getPlaylists)
        .map(playlists => !!playlists)
        .take(1);
}

hasPlaylists(): Observable<boolean> {
    console.log('pew pew'); // nothing happens here =(
    return this.hasPlaylistsInStore()
        .switchMap(inStore => {
            if (inStore) {
                return of(inStore);
            }

            return this.getPlaylistsFromApi();
        });
}

canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
    return this.waitForCollectionToLoad()
        .switchMap(() => this.hasPlaylists());
}
}

加载的属性存在于减速器中并被选中。сcode执行没有达到hasPlaylists函数所以我认为switchMap不起作用,但我不明白为什么=)

UPD:添加了路由器声明

import {
    PlaylistsExistsGuard
} from './guards';
{
     path: 'playlists',
     component: MusicComponent,
     canActivate: [PlaylistsExistsGuard]
}

UPD:我想我找到了解决方案。如果我使用地图而不是在这里过滤

 waitForCollectionToLoad(): Observable<boolean> {
    return this.store.select(fromRoot.getPlaylistsLoaded)
        .map(loaded => loaded) //here
        .take(1);
}

并在这里采取行动:

getPlaylistsFromApi(): Observable<boolean> {
    this.store.dispatch(new playlists.GetPlaylistsAction());
    return this.actions$
        .ofType(playlists.GET_PLAYLISTS_COMPLETE)
        .mapTo(true);
}

UPD:正如@Skeptor 在评论中建议的那样,我不需要map获取元素,所以我可以在这里删除它

waitForCollectionToLoad(): Observable<boolean> {
    return this.store.select(fromRoot.getPlaylistsLoaded)
        .take(1);
}

守卫工作正常,但我仍然不明白为什么它不能与过滤器一起使用=/

4

0 回答 0