在我的应用中,我想在顶部导航中调用服务,但我的authguard不断告诉我我尚未登录。我认为这与路由有关,但我似乎无法弄清楚
我的应用HTML:
<app-top-nav></app-top-nav>
<div id="container">
<router-outlet></router-outlet>
</div>
TopNav组件:
export class TopNavComponent {
myArray;
someString;
subscription: Subscription;
constructor(
private myService: MyService) {
this.myArray = [];
this.someString = '';
}
ngAfterViewInit() {
this.getSomeData();
}
getSomeData() {
this.subscription = this.myService.get().subscribe(
myArray => this.myArray = myArray
);
}
}
MyService.ts
interface PagedResult<T> {
Items: T[];
Count: number;
}
@Injectable({
providedIn: 'root'
})
export class BedrijfService {
private url = 'https://someurl.com/api';
private myUrl = this.url + '/combos/Data2?UseAuthorization=false';
constructor(private httpClient: HttpClient) { }
get() {
return this.httpClient.get<PagedResult<SomeData>>(this.url);
}
}
这是我的app.routing
const routes: Routes = [
{
path: '',
pathMatch: 'full'
},
{
path: 'auth-callback',
component: AuthCallbackComponent
},
{
path: 'somepath',
loadChildren: './somepath/somepath.module#SomepathModule',
canActivate: [AuthGuardService]
},
{
path: '**',
component: NotFoundComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
'SomePath'可以正常工作,我只是不知道如何处理顶级导航组件。
这是我的AuthGuard服务:
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(private authService: AuthService) { }
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
if (await this.authService.isLoggedInAsync()) {
return true;
}
window.sessionStorage.setItem('portal_return_url', state.url);
this.authService.startAuthentication();
return false;
}
}
我在顶部导航栏中的服务网址被调用,但是我不断收到未授权的错误。
答案 0 :(得分:0)
尝试使用
ngOnInit() {
this.getSomeData()
}
代替ngAfterViewInit()
答案 1 :(得分:0)
我自己解决了问题,所以将解决方案留在这里。 我的服务已在AuthGuard之前加载。
async ngAfterViewInit() {
if (await this.authService.isLoggedInAsync()) {
this.getSomeData();
return true;
}
}