gpt4 book ai didi

javascript - 如何在加载组件 Angular 4 之前获得服务响应?

转载 作者:太空狗 更新时间:2023-10-29 17:56:49 25 4
gpt4 key购买 nike

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

我在 Angular 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 应该返回 truefalse,并且根据这个值,路由将被激活或不激活。现在你必须将这个 auth guard 添加到你的路由中(这里是激活子路由的示例)。如果您想在组件加载之前获取数据,您可以使用解析器

解析器

/* 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*/

关于javascript - 如何在加载组件 Angular 4 之前获得服务响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47367738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com