4

我有一个向 api 发出请求的服务,根据它的响应,我应该决定是否必须加载一个组件。但是由于接收响应花费了时间,组件加载而不考虑响应状态,并且在收到响应一段时间(大约 0.5 秒)后,如果必须不加载组件,我们导航到其他地方。我不希望在收到响应之前加载组件。

我在角度 4 中使用来自AuthGuard的canActivate函数,如下所示:

export class AuthGuard implements CanActivate {
access = true;
res: any;

constructor(private router: Router, private routeService: RouteService){}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    setTimeout(() => {
        if( !this.exept.includes(this.router.url) ){
            this.routeService.FormOperation(this.router.url).subscribe(item=> {
                this.res = item;
                if (this.res.status == 200) {
                    if (this.res.data.Access[1] == false) {
                        this.access = false;
                    }
                    if (this.access == true)
                    {
                       return true;
                    }
                else {
                    this.router.navigate(['/dashboard']);
                    return false;
                }
            })
        }
    },0);

    if (sessionStorage.getItem('token') && this.access)
    {
        // logged in so return true
        return true;
    }

    // not logged in so redirect to login page with the return url
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
    return false;
}

我正在使用setTimeout以便获得正确的this.router.url

更新:

我添加了解析器,如下所示:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): void {

    this.routeService.FormOperation(this.router.url).toPromise()
        .then(response => {
            this.form_operation_data = response;

            if(!this.form_operation_data['data']['Access'][1]) {
                this.router.navigate(['/dashboard']);
            }
        })
        .catch(err => {
            console.error(err);
        });
}

但组件仍然在响应数据接收之前加载......

4

1 回答 1

2

你已经很接近了:你的 AuthGuard 应该返回trueor false,并且基于这个值,路由将被激活或不被激活。现在您必须将此身份验证保护添加到您的路由中(这是激活子路由的示例)。如果你想在组件加载之前获取数据,你可以使用resolvers

解析器

/* Imports */
@Injectable()
export class DataResolverService {

  constructor(
    private _serviceToShareData: ServiceToShareData,
    private _serviceToGetData: ServiceToGetData,
  ) { }

  /* An example with Promise */
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<void> {
    return this._serviceToGetData.anyRequestToApi()
      .then(response => this._serviceToShareData.setData(response))
      .catch(err => {
        console.error(err);
      });
  }
}

现在,您可以从组件中的 ServiceToShareData 服务获取获取的数据,并使用这些数据加载这些数据。

路由模块

/* Other imports */
import {DataResolverService } from './path-to-service/data-resolver-service'
import {AuthGuard} from './path-to-service/auth-guard'

const routes: Routes = [
  {
    path: 'app',
    component: ParentComponent,
    children: [
      {
        path: 'child-route',
        component: childRouteComponent,
        canActivate: [AuthGuard],
        resolve: {
          data: DataResolverService
        }
      }
    ]
  }
];

/* Other stuff like @NgModule and class export*/
于 2017-11-18T15:48:45.237 回答