Route Guard: How can I set true or false based on params set from HttpPost?

只谈情不闲聊 提交于 2020-01-16 12:02:47

问题


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));


来源:https://stackoverflow.com/questions/51818528/route-guard-how-can-i-set-true-or-false-based-on-params-set-from-httppost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!