![](/img/trans.png)
[英]Angular router.navigate doesn't route to resolver if on same component
[英]Angular router doesn't navigate for the first time from component to component
我希望在注册后从注册组件重定向到挑战组件。 如果本地存储未设置到质询组件,它将重定向到注册组件。 我的问题是它第一次注册时不会从注册导航到挑战组件。
challange.component.ts
ngOnInit() {
if(localStorage.getItem('userId') != null) {
......
}
else{
this.router.navigate(['/signup']);
}
}
signup.component.ts
signupNew() {
this.signupService.doSignup(this.parameter);
this.router.navigate(['/challange']);
}
signup.service.ts
doSignup(signParam : SignupParam) {
this.signupCollection.add(signParam).then(ref => {
localStorage.setItem('userId', ref.id);
console.log(localStorage.getItem('userId'))
}).catch(err => {
console.log('Check your Internet connection...');
})
}
route.ts
export const appRoutes : Routes = [
{ path : 'signup', component : SignupComponent },
{ path : 'challange', component: ChallangeComponent},
{ path : 'feed', component: NewsFeedComponent},
{ path : 'items-initial', component: InitialItemComponent},
{ path: '', redirectTo: '/', pathMatch : 'full'}
];
我想你的问题在这里:
this.signupService.doSignup(this.parameter);
this.router.navigate(['/challange']);
doSignup
是异步的,你没有同步它,所以路由器在 userId
设置在本地存储之前导航到/challange
,这导致第一次重定向。 但是,此时, userId
将位于localStorage中。 同步这些调用:
async doSignup(signParam : SignupParam) {
// error handling omitted
const ref = await this.signupCollection.add(signParam);
localStorage.setItem('userId', ref.id);
}
async signupNew() {
await this.signupService.doSignup(this.parameter);
this.router.navigate(['/challange']);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.