logo
Tags down

shadow

What may happen if you don't unsubscribe from an Observable in canActivate of a guard?


By : Atanas Feimov
Date : September 18 2020, 01:00 PM
Does that help Nothing will happen, the same behaviour you experience will be preserved. I guess this question is angled more towards the "cost" of not unsubscribing.
Under the hood, angular adds the first operator to the observable, which completes the observable after emitting the first value.
code :


Share : facebook icon twitter icon

Angular 4 CanActivate guard doesnt load component with used with service; simple Observable.of(true) works


By : zx y
Date : March 29 2020, 07:55 AM
wish helps you Observable is not promise any return code in subscribe will not work. change code to this.
code :
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
//return Observable.of(true);
return this._userService.verify().switchMap((result: Array<Object>) => {
    let user : UserDetail = new UserDetail();
    Object.keys(user).forEach(key=>{
         let listValue = result.filter(m=>m["m_type"]==key);
         if(listValue.length>0){
            user[key] =  result.filter(m=>m["m_type"]==key)[0]["m_value"];
         }
    });
    this.userDetails = user;
    return Observable.of(true);
    //return true;
}).catch(() => {

    // error when verify so redirect to login page with the return url
    this._router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
    return Observable.of(false);


});

Return observable inside observable in canactivate guard of Angular 4


By : mmmcfly
Date : March 29 2020, 07:55 AM
it helps some times As Christian mentioned in a comment, you should be using switchMap to chain your observables together.
In your first implementation you are not returning your inner observable therefore the router never subscribes to it, so it never gets called.
code :
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {

    return this.oidcSecurityService.getIsAuthorized()
      .switchMap(
        data => {
          if (data === false) {
            this.router.navigate(['/login']);
            return Observable.of(false); // user not logged in, canActivate = false
          }else if (data === true) {
            const roles = route.data['roles'] as Array<string>;
            if (roles) {
              // return inner observable
              return this.profileService.getObservableUserProfileFromServer()
                .map(userProfile => {
                  const userRoles = userProfile.Roles;
                  for (const role of roles) {
                    if (userRoles.indexOf(role) > -1) {
                      // role found, canActivate = true
                      return true;
                    }
                  }
                  // no matching role, canActivate = false
                  return false;
                });
            }else{
              // no roles defined in route data, canActivate = false
              return Observable.of(false)
            }
          }
        }
      }
    );

}

Angular5 canactivate guard :Types of property 'canActivate' are incompatible


By : ram1050
Date : March 29 2020, 07:55 AM
it fixes the issue I think the problem is the declaration of state: should be RouterStateSnapshot
code :
interface CanActivate { 
   canActivate(route: ActivatedRouteSnapshot, 
               state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean
}

Angular guard canActivate method dont work with Observable<boolean>


By : Ayomi Dassanayake
Date : March 29 2020, 07:55 AM
Hope that helps I'm trying to verify a token in the back end before accessing a route , You're not returning your observable:
code :
this.authService.isTokenValid(token)
  //...
return this.authService.isTokenValid(token)
  //... 

Angular8 AngularFireAuth: authState.map for Guard canActivate() error: Property 'map' does not exist on type 'Observable


By : user3396272
Date : March 29 2020, 07:55 AM
To fix this issue I have an error with Angular8 AngularFireAuth when trying to define canActive() on a guard
code :
import { Injectable } from "@angular/core";
import { CanActivate, Router } from '@angular/router';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators'

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private router: Router, private afAuth: AngularFireAuth) { }

  canActivate(): Observable<boolean> {
    return this.afAuth.authState.pipe(map((user)=>{
      if(user) {
        return true;
      }
      this.router.navigate(['/login'])
      return false;
    }))
  }
}
Related Posts Related Posts :
  • Kubernetes internal CORS issues between services
  • Ionic set marker on location or based on longitude and latitude
  • CAN NOT expand Angular Material table
  • Share a angular library across multiple projects
  • How to import pipe to 2 modules(AppModule and ChildModule)?
  • How to disable the drag option on Angular material Slide toggle component
  • Does Spartacus support Hybris on-premise?
  • Bind regular expression from json to typescript
  • How can i get the selected value in ion-alert radio alert
  • How to get all attributes of an object
  • Using angular elements inside the same angular project
  • RxJS assign observable and get data in one stream
  • Why I can not use anguar/material elements?
  • Getting Error when running 'ng test' Command
  • How can I make another request within catchError?
  • angular 7 input number validation
  • Dont show digits after decimal using angular pipe
  • How to use same component in normal way and with angular material dialog both?
  • How to integrate ReSharper with WebStorm
  • Google cloud application yaml for angular 7
  • How to perform concurrent HTTP requests on rows of a table
  • Angular 7 - deploy workspace applications (projects) in isolation
  • how to turn off differential loading in Angular v8?
  • How to add and update npm packages for a new Angular app in Visual Studio 2019
  • Angular 7, Ngrx, Rxjs 6 - Accessing state between lazy loaded modules
  • cannot find symbol import com.google.firebase.iid.FirebaseInstanceIdService error in ionic3
  • AWS CodePipeline, build failed and getting error
  • CORS problem with Angular and laravel even after setting the CORS header and server response
  • Angular, when the variable is mentioned in the url, the variable is not replaced with its value. Ex: ${username}
  • How to apply two ngIf on single html element with two different conditions
  • Ionic not importing ngx-mathjax module
  • How to display base64 image on iPhone in Ionic 4
  • ngFor in columns with diferents properties
  • How catch the http errors with map
  • How to format a Date field in Angular project
  • focusing ng-select filter input on drop down open
  • Angular 7 PDFJS Component
  • NestJs Errors stemming from @types dependencies in node_modules when running start:prod on fresh project
  • How to override ion-back-button action in ionic 4 with angular 7
  • How can I have an array in input form?
  • Angular 6 component test with a variable into HTML
  • Why is ES7/array polyfill needed despite the tsconfig target is set to ES5
  • How to deal with Google recaptcha backend validation response delay
  • Logging in using @angular/fire/auth results in 403 error on localhost
  • In Angular, with ViewChild/ ViewChildren, how do I get the child of a child?
  • Material Dialog Close on mouseleave (angular material)
  • Ngx-Datatable - How to handle a boolean data of a row
  • Send data post in angular
  • Expected Arguments 1-3, but got 0
  • Immediate response after subscribtion
  • Convert JSON array received from API to JSON Object in Angular
  • Ionic 4 with angular 7, Cannot find type definition file for '@types'
  • ngrx effects property payload does not exist on type never
  • Child component life cycle in parent component
  • How to make custom wrapper for 2 field groups with ngx-formly?
  • Subject.subscribe not firing in ngOnInit
  • Angular Nginx Docker 404
  • I have 'expression changed after it has been checked error 'if I use *ngif, but it not appears if i use [hidden]
  • Selection animation doesn't work for Angular (7) Material Tabs
  • Create Component without folder
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk