Executing parallel observable requests in Angular2/Ionic2

Hello, I am new to working with angular2 and ionic2. My goal is to make two requests sequentially after a successful login request.

After a successful login, I want to verify if the returned token has the necessary access rights on the server and redirect the user accordingly.

Below is the code I have tried, but it is not working as expected:

  redirrect(token: string) {

//console.log(token)  returns value of the token

       if (this._authservice.checkAccessRights(token, "is-marshal")) {
           this._navCtrl.setRoot(MarshalPage);

      } else if(this._authservice.checkAccessRights(token, "can-read")) {

           this._navCtrl.setRoot(UserPage);

      } else {

      //force logout then redirrect to login page
         return this._authservice.logout()
            .subscribe(() => {
            this.showtoast("No access rights");
            this._navCtrl.setRoot(LoginPage);
         },
       error=>this.handleError())
    }

   }

Code snippet for the _authservice:

  checkAccessRights(usertoken: string, permission: string): Observable<any>             
    {
         let headers = new Headers();
         headers.append('Authorization', 'Bearer ' + usertoken);

      return this._http.post(this.authurl +"can-access",permission)
       .map((response: Response) => {
           return response;  //this response is true or false from server
         });
   }

Answer №1

validateAccess function returns an observable that requires subscription to handle true/false values. Avoid simply checking the return of the observable.

Consider this approach:

    redirectTo(token: string) {

    // The console.log(token) will display the value of the token

          this._authservice.validateAccess(token, "marshal").subscribe(
              result=>{
               result?
                  this._navCtrl.setRoot(MarshalPage):
                       this._authservice.validateAccess(token, "reader").
                       subscribe(result=>{
                        if(result)
                         this._navCtrl.setRoot(UserPage);
                        else
                          this._authservice.logout()
                              .subscribe(() => {
                                this.showToast("Insufficient access rights");
                                this._navCtrl.setRoot(LoginPage);
                                },
                               error=>this.handleError());

          // User forced to logout and redirected to login page

                         });

          });
}

Using switchMap:

  redirectTo(token: string) {


             canRead$ = this._authservice.validateAccess(token, "reader").switchMap(result=>result?Observable.fromPromise(this._navCtrl.setRoot(UserPage)).mapTo(true)):
    this._authservice.logout().mapTo(false));

             marshal$ = this._authservice.validateAccess(token, "marshal").switchMap(result=>{result? Observable.fromPromise(this._navCtrl.setRoot(MarshalPage)).mapTo(true):
    canRead$);
                        marshal$.subscribe(result=>{
                             if(!result){
                                    this.showToast("Insufficient access rights");
                                    this._navCtrl.setRoot(LoginPage);
                                    },
                                   error=>this.handleError());

              // User forced to logout and redirected to login page

                             });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the benefits of useContext in Expo router

Currently, I am working with the latest Expo-Router version which incorporates file-based navigation. To establish a universal language context in my application, I have utilized React's context API along with the useReducer hook. However, I am encoun ...

How can you specify a tuple type in TypeScript for an array that is empty?

I'm attempting to convert a const object into a class in order to create readonly properties. The goal is to ensure that the values in these properties never change. Specifically, I'm trying to create a module property in my class that is define ...

Using Typescript to Import One Namespace into Another Namespace

Is it possible to export a namespace from one typescript .d.ts file and then import that namespace into another .d.ts file where it is utilized inside of a namespace? For instance: namespace_export.d.ts export namespace Foo { interface foo { ...

Angular RxJS: The never-ending reduction

I have developed a component that contains two buttons (searchButton, lazyButton). The ngOnDestroy method is defined as follows: public ngOnDestroy() { this.unsubscribe$.next(); this.unsubscribe$.complete(); } I have created two observables from ...

Is there a way to instruct Alexa/Jovo to incorporate just one render document in its response?

Within my project, there are multiple outputs, but I am specifically focused on an output that presents 2 directives: an APL and an APLA render document. My component is set up to handle this in the following way: @Handle({ global: true, prioritiz ...

Deduce the Prop Component Type by Examining the Attribute Type

I am facing an issue with a component that requires a `labels` attribute. <Component defaultValue={FURNITURE.BED} labels={[ { value: FURNITURE.BED, text: 'Bed', }, { value: FURNITURE.COUCH, text: 'C ...

Tips for writing unit tests for an object with a type union in TypeScript, Karma, and Sinon

Currently, I am conducting unit-testing for a project that utilizes TypeScript with the Angular framework. I am using Karma with Mocha and Chai frameworks for this purpose. The project includes an interface for the object, defined as follows: interface IS ...

Is there a way to ensure that Tailwind CSS loads before rendering components in NextJS?

While developing my web application, I encountered an issue with the tailwind CSS styling. The styles seem to load correctly, but there is a slight delay before they take effect. This results in users seeing the unstyled version of the website briefly befo ...

Wait for Protractor until the page has completely finished loading

After navigating to https://docs.angularjs.org/tutorial, I attempted to click on '0 - Bootstrapping' under Tutorial but Protractor did not wait for the page to fully load, resulting in an Error. Error: Failed to execute 'click' on &a ...

The utilization of conditional expression necessitates the inclusion of all three expressions at the conclusion

<div *ngFor="let f of layout?.photoframes; let i = index" [attr.data-index]="i"> <input type="number" [(ngModel)]="f.x" [style.border-color]="(selectedObject===f) ? 'red'" /> </div> An error is triggered by the conditional ...

Utilizing Bootstrap.css in various Angular modules

Is there a way to utilize bootstrap.css in specific modules rather than applying it to the entire application? I wish to avoid adding Bootstrap.css to index.html or styles of angular.json, and only use it in certain modules. In my project, I have two dis ...

Guide on saving a PDF file after receiving a binary response using axios

Is there a way to save a PDF file from a binary response received through an axios get request? When making the request, I include the following headers: const config: AxiosRequestConfig = { headers: { Accept: 'application/pdf', respon ...

Nuxt - It is not possible to use useContext() within a watch() callback

I'm currently utilizing version 0.33.1 of @nuxtjs/composition-api along with Nuxt 2. Here's a snippet from my component: import { defineComponent, useContext, useRoute, watch } from '@nuxtjs/composition-api'; export default defineCompo ...

Cannot locate: Unable to find the module '@react-stately/collections' in the Next.js application

While working on my Next.js app, I decided to add the react-use package. However, this led to a sudden influx of errors in my Next.js project! https://i.stack.imgur.com/yiW2m.png After researching similar issues on Stackoverflow, some suggestions include ...

Navigating the world of Typescript: mastering union types and handling diverse attributes

I am currently working on building a function that can accept two different types of input. type InputA = { name: string content: string color: string } type InputB = { name: string content: number } type Input = InputA | InputB As I try to impleme ...

Encountered a hiccup when attempting to include the DatePicker component in app.module.ts using

I'm encountering an issue with some providers in my app.module.ts file. Specifically, when trying to use the DatePicker component, I'm getting this error message: Type 'DatePickerOriginal' is not assignable to type 'Provider'. ...

Angular and Bootstrap do not support margin styles

While working with Angular 5 and Bootstrap, I have encountered an issue with using inline styles for margin. The template I am using is as follows: @Component({ selector: "dynamic-container-component", template: ` <div styl ...

Exploring the SOLID Design Principles through TypeScript

Recently, I came across an intriguing article discussing the SOLID principles and delving into the concept of the Dependency Inversion Principle (DIP). The article presented an example to illustrate this principle using both an incorrect and a correct appr ...

You cannot employ typed arguments in combination with Typescript within the VueJS framework

I'm struggling to develop a typescript vue component with some methods. Here is the script snippet. <script lang="ts"> import Vue from 'vue'; export default Vue.extend({ methods: { check(value: number) { console.log(valu ...