Angular 5 HTTP请求处于保护状态

时间:2019-05-27 10:58:40

标签: javascript angular typescript httprequest guard

我正在尝试在守护程序中调用http GET请求。可能由于同步而无法正常工作...我基本上得到的链接是具有登录用户ID的访问权限。我在做什么错了?

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AppService } from '../app.service';
import { CookieService } from 'ngx-cookie-service';
import { AuthService } from '../services/auth.service';
import { LinkService } from '../services/link.service';



@Injectable()
export class ManageProjectUsersGuard implements CanActivate {
links: any[] = [];

constructor(
    private auth: AppService,
    private router: Router,
    private authService: AuthService,
    private linkService: LinkService
) { }

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {


    var selectedProject = this.authService.getProjectIdFromUrl(state.url);
    if (!selectedProject) {
        selectedProject = this.authService.getSelectedProject();
    }
    var user = JSON.parse(localStorage.getItem("user"));
    if (!user || !user.username || !selectedProject) {
        return false;
    }
    return this.linkService.getLinksByUsername(user.username).map((links) => {
        this.links = links;
        console.log(this.links)
        var flag = false

        for (let i = 0; i < this.links.length; i++) {
            if (this.links[i].project.id == selectedProject && this.links[i].user.username == user.username) {
                if (JSON.parse(JSON.stringify(this.links[i])).role.id == 2) {

                    flag = true;
                    return flag; // access allowed
                }
            }
        }
        return flag; // access denied
    });
  }

}

0 个答案:

没有答案