首页 > 解决方案 > 如何有效访问路由器存储参数?

问题描述

我的效果是我需要传递从我的 URL 获得的 ID。

我有一个包含我的路由器存储的根存储,并且我有另一个存储用于我的组件,以加载一些数据。

1. 如何从我的效果内的路由器商店访问 URL 参数?

2.我的组件效果是否可以访问根存储中的数据?

3. 现在我有 24322 硬代码,我需要从我的根存储中获取它。我应该得到它的效果还是将它传递到有效负载上更好?*

这是我的组件效果的代码

import { Injectable } from '@angular/core';

import { Effect, Actions, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { map, switchMap, catchError } from 'rxjs/operators';

import * as fromRoot from '../../../store';
import * as topicActions from '../actions/topic.actions';
import { PostsService } from '../../../service/posts.service';

// need to connect with roter store
@Injectable()
export class TopicEffects {

    @Effect()
    loadTopic$ = this.actions$
        .pipe(
            ofType(topicActions.LOAD_TOPIC),
            switchMap(() => {
                return this.postService.getTopicHeader(24322).pipe(
                    map(topic => new topicActions.LoadTopicSuccess(topic)),
                    catchError(error => of(new topicActions.LoadTopicFail(error)))
                );
            })
        );

    constructor(private readonly actions$: Actions, private readonly postService: PostsService) {}

}

标签: angularngrxngrx-router-store

解决方案


要从您的商店访问一个值,您可以将您的商店注入您的 TopicEffects 中,然后使用 withLatestFrom 运算符。 https://www.learnrxjs.io/operators/combination/withlatestfrom.html

它看起来像这样:

@Effect()
loadTopic$ = this.actions$
.pipe(
    ofType(topicActions.LOAD_TOPIC),
    withLatestFrom(this.routerStore.pipe(select(selectSomeValue)))
    switchMap(([action, valueFromStore]) => {
        return this.postService.getTopicHeader(valueFromStore).pipe(
            map(topic => new topicActions.LoadTopicSuccess(topic)),
            catchError(error => of(new topicActions.LoadTopicFail(error)))
        );
    })
);

这是在回答你的问题吗?


推荐阅读