0
votes

In my Angular application I have an effect (handled when the application starts) that retrieve the available langs from the server. I'm going to save the lang[] inside an object (GlobalData) saved in the application Store. In the login component I subscribe to the property isFetchingLangs, a boolean, that if it is true it will disable the login. So the steps of the effects are the following:

  1. Get the GlobalData from store
  2. If there are langs set the isFetchingLangs to false and save the fact that the GlobalData is created; otherwise call the service;
  3. Preparing the actions to dispatch: if the GlobalData is not present, I add the langs and add the action to save GlobalData. set the isFetchingLangs to false

This is the code:

coreActions$ = this.actions$
    .ofType(CoreActions.GET_AVAILABLE_LANGS)
    .pipe(
        withLatestFrom(this.store.select(fromApp.getGlobalData))
        , take(1) 
        , map(([action, storeState]) => {
            if (storeState && storeState.langs && storeState.langs.length) {
                this.globaDataCreated = true;
                return this.store.dispatch(new CoreActions.GetAvailableLangsFinished());
            } else {
                return from(this.langsService.getAvailableLangs());
            }
        })
        , mergeMap((langs: Lang[]) => {
            let actions = [];
            if (!this.globaDataCreated) {
                this.applicationUrl = this.urlService.getApplicationUrl();
                let newGlobalData = new GlobalData(
                    false,
                    null
                );

                langs.forEach(lang => {
                    newGlobalData.langs.push(lang)
                });
                this.translate.use('en');
                this.moment.tz.setDefault("UTC");
                actions.push({
                    type: CoreActions.SET_CORE_APPLICATION_DATA, 
                    payload: newGlobalData
                })
            }

            actions.push({
                type: CoreActions.GET_AVAILABLE_LANGS_FINISHED
            })

            return actions;
        })
        , catchError((err, caught) => { ...... }

The service:

getAvailableLangs(): any {
    return this.http.get<CommonClasses.SenecaResponse<CommonClasses.Lang[]>>(this.applicationData.applicationContext + 'rest-api/langs');
}

Issue: it enters in the mergeMap((langs: Lang[]) => { ....} before to call the service this.langsService.getAvailableLangs()

Target: wait untile the getAvailableLangs() finished, and then set isFetchingLangs to false and do other operations

****** EDITED CODE AFTER @JANRECKER ANSWER *********

getAvaibleLang(storeState?: GlobalData) {
    if (storeState && storeState.langs && storeState.langs.length) {
        return this.store.dispatch(new CoreActions.GetAvailableLangsFinished());
    } else {
        return this.langsService.getAvailableLangs();
    }
}

@Effect()
coreActions$ = this.actions$
    .ofType(CoreActions.GET_AVAILABLE_LANGS)
    .pipe(
        withLatestFrom(this.store.select(fromApp.getGlobalData))
        , take(1) 
        , switchMap(([action, storeState]): Lang[] => this.getAvaibleLang(storeState))
        , mergeMap(
            (langs: Lang[]) => {
                if (langs) {
                    const applicationUrl = this.urlService.getApplicationUrl();
                    let newGlobalData = new GlobalData(
                        applicationUrl,
                        false,
                        null
                    );
                    langs.forEach(lang => {
                        newGlobalData.langs.push(lang)
                    });
                    this.translate.use('en');
                    return [{
                        type: CoreActions.SET_CORE_APPLICATION_DATA,
                        payload: newGlobalData
                    }, {
                        type: CoreActions.GET_AVAILABLE_LANGS_FINISHED
                    }];
                } else {
                    return [{
                        type: CoreActions.GET_AVAILABLE_LANGS_FINISHED
                    }];
                }
            }
        )
        , catchError((err, caught) => {....}
1

1 Answers

0
votes

Be aware, that "map" changes the content of the stream.

of('helloWorld').pipe(
    map((data:string):number => data.length) // data.length = 10
).subscribe(
    (data:number) => console.log(data) )  // 10
)

You wrote something like (i use typings to make it a bit more obvious)

of('helloWorld').pipe(
    map((data:string):Observable<number> => from(data.length))
).subscribe(
    (data:Observable<number>) => ... )
)

So you created an observable in an observable stream. :-)

If you want to open a second stream, "mergeMap" would be the right choice. If the first stream did all you want, and you want to work now on a different stream "switchMap" would be my choice.

Just to get a better feeling of the code, i would extract everything out of the stream into methods. Something like

coreActions$ = this.actions$
    .ofType(CoreActions.GET_AVAILABLE_LANGS)
    .pipe(
        withLatestFrom(this.store.select(fromApp.getGlobalData))
        , take(1)
        ,switchMap(([action,storeState]):Lang[] => this.getAvaibleLang(storeState) )
        ,tap(() => this.setApplicationUrl() )
        ,tap((langs:Lang[])=> this.setLanguages(langs) )
        ,tap(()=> this.pushLanguageAction() )
   )

With the intensive use of typeings, i think it gets more readable.

warm regards