微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何在加载组件Angular 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);
        });
}

但仍然在响应数据收到之前加载组件……

解决方法:

您是如此接近:您的AuthGuard应该返回true或false,并且基于此值,路由将被激活或不激活.现在您必须将此auth guard添加到您的路由(这是激活子路由的示例).如果要在组件加载之前获取数据,可以使用解析器.

分解器

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

  constructor(
    private _servicetoShareData: ServicetoShareData,
    private _servicetoGetData: ServicetoGetData,
  ) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): void {
    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*/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐