user13314476
user13314476

Reputation: 133

How to pass varaible in pipe rxjs?

There is a code that first loads config file then scripts and as result gets token:

 return configService.loadConfig().pipe(
      (tap((config: Config) => {
        const { mapUrl, panoramaUrl, configAuth, backendUrl, backendGuid } =
          config;
        const url = `${backendUrl}/${configService.user_auth_url}`;
        scriptService.set([configAuth, mapUrl, panoramaUrl]);
      }),
      switchMap(() => from(scriptService.load(scriptService.get()))),
      switchMap(() => authService.loadToken(url, backendGuid)))
    );

Problem is I can not get access for url, backendGuid in last switchMap.

I have tried this:

return configService.loadConfig().pipe(
      map((config: Config) => {
        const { mapUrl, panoramaUrl, configAuth, backendUrl, backendGuid } =
          config;
        return {
          mapUrl,
          panoramaUrl,
          configAuth,
          backendUrl,
          backendGuid,
        };
      }),
      switchMap(({ mapUrl, panoramaUrl, configAuth }) =>
        from(
          scriptService.load(
            scriptService.set([configAuth, mapUrl, panoramaUrl])
          )
        )
      ),
      switchMap(({ mapUrl, backendGuid }) =>
        authService.loadToken(mapUrl, backendGuid)
      )
    );

Problem is the last switchMap has not { mapUrl, backendGuid }

Upvotes: 0

Views: 48

Answers (1)

Picci
Picci

Reputation: 17762

You can try something like this

 return configService.loadConfig().pipe(
      // use map rather than tap so that you can pass a value to the next operator
      (map((config: Config) => {
        const { mapUrl, panoramaUrl, configAuth, backendUrl, backendGuid } =
          config;
        // move the definition of the const url downstream
        // const url = `${backendUrl}/${configService.user_auth_url}`;
        scriptService.set([configAuth, mapUrl, panoramaUrl]);
        // return the data read from the configuration
        return config;
      }),
      // config now is a input parameter for the function passed to switchMap
      switchMap((config) => from(scriptService.load(scriptService.get()))
      // when the scripService.get() emits then we trigger a map that returns
      // the config value received from upstream
      .pipe(
        map(() => config)
      ),
      switchMap((config) => {
        const { mapUrl, panoramaUrl, configAuth, backendUrl, backendGuid } =
          config;
        // here we define the const url
        const url = `${backendUrl}/${configService.user_auth_url}`;
        authService.loadToken(url, backendGuid)
      })
    );

Upvotes: 1

Related Questions