如何两次调用以ngrx效果调用的服务?

时间:2019-09-19 21:00:50

标签: angular typescript redux rxjs ngrx

我有一个正在监听动作的效果,这种效果是一次调用api(检索10个随机电影),这是正常现象,但是我想两次调用相同的服务。

loadMovies$ = createEffect(() => this.actions$.pipe(
   ofType('[Movies Page] Load 20 Movies'),
   mergeMap(() => this.moviesService.getTenRandomMovies()
      .pipe(
        map(movies => ({ type: '[Movies API] 10 Movies Loaded Success', payload: movies })),
        catchError(() => EMPTY)
     ))
   )
 );

我在考虑这种解决方案,但看起来很奇怪。让我知道这是否是唯一的可能性。

 dispatchTwiceGetAuthQuestions$ = createEffect(() =>
    this.actions$.pipe(
        ofType('[Movies Page] Load 20 Movies'),
        tap(() => {
          this.store.dispatch(new LoadTenRandomMovies()); 
        }),
        tap(() => {
            this.store.dispatch(new LoadTenRandomMovies()); 
        })
    )
);


loadMovies$ = createEffect(() => this.actions$.pipe(
   ofType('[Movies Page] Load 10 Movies'),
   mergeMap(() => this.moviesService.getTenRandomMovies()
      .pipe(
        map(movies => ({ type: '[Movies API] 10 Movies Loaded Success', payload: movies })),
        catchError(() => EMPTY)
     ))
   )
 );

注意:无法更新后端。

2 个答案:

答案 0 :(得分:0)

您可以编写一个新功能moviesService.getRandomMovies(pagesToGet: int)

let observables: any[] = [];

for (let i = 0; i < pagesToGet; i ++)
{
    observables.push(this.getTenRandomMovies());
}

return forkJoin(observables)
    .pipe(map(results => results.flat()))

答案 1 :(得分:0)

使用forkJoin应该足够

import React, { Component } from 'react';
import axios from 'axios';


const Consultant_information = props => (
    <div>
        <p>Employee Name: {props.consultant_information.employee_name}</p>
        <p>Employee Title: {props.consultant_information.title}</p>
    </div>
)

export default class Detail_consultant extends Component {
    constructor(props) {
        super(props);

        this.state = {consultants: []}
    }

    componentDidMount() {
        axios.get('http://localhost:5000/consultants/' + this.props.match.params.id)
        .then(response => {
            this.setState({ consultants: response.data })
        })
        .catch((error) => {
            console.log(error);
        })
    }

    detailConsultant() {
        return this.state.consultants.map(currentconsultant => {
            return <Consultant_information consultant_information={currentconsultant} key={currentconsultant._id}/>;
        })
    }

    render() {
        return (
            <div className='consultant-page'>
                { this.detailConsultant() }
            </div>
        )
    }

}