Route Guard: How can I set true or false based on

2019-08-23 05:02发布

问题:

My code:

@Injectable()

export class UserRouteAccessService implements CanActivate {

    authorized = [
        'AGREEMENTS_VIEW',
        'PROSPECTS_VIEW',
        'AGREEMENTS_INSERT_UPDATE',
        'PRODUCTS_INSERT_UPDATE',
        'PROSPECTS_INSERT_UPDATE',
        'DOCUMENTS_VIEW',
        'DOCUMENTS_INSERT_UPDATE',
    ];

    constructor(private router: Router, private securityService: CralSecurityService) {
    }



    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        //boolean var


        this.securityService.securityActions().subscribe(
            data => {
                //control if auth. is correct

                //if yes set true
                //if not set false
            },
            error => {
                //return an error
            }
        )
        //return boolean
    }
}

The comments are what id like to do but i cant really know what should i write since this is my first time working with angular 4.

Basically I want to set True if some of the params from authorized are sent and false if there are no params in the service.

I hope this is clear, if you need more infos tell me :)

Service:

securityActions(): Observable<any> {
    return this.http.post<Observable<any>>(
        `${this.ENDPOINT}/security-actions`,
        null,
    );
}

回答1:

You want to return a boolean, but the boolean can only be obtained asynchronously. So you can't return a boolean. Fortunately, as you can see in the return type of the method, you can return an Observable<boolean>. An Observable (or a promise) is precisely used to do that: return an asynchronous result.

So, don't subscribe to the observable returned by securityActions(). Instead, transform the observable into an Observable, using the map() and the catchError() operators:

return this.securityService.securityActions().pipe(
    map(data => {
            //control if auth. is correct

            //if yes set true
            //if not set false
    },
    catchError(() => of(false))
);

Note: if you're still using an old version of Angular and RxJS, then you should upgrade. If you really can't yet, you'll need to adapt the above code to the old version of RxJS you're using:

// TODO import the required operators, as documented in your old version of RxJS

return this.securityService.securityActions().map(
    data => {
            //control if auth. is correct

            //if yes set true
            //if not set false
    }
).catch(() => of(false));