我在我的Nativescript应用程序中使用nativescript-urlhandler。 当我放置路由器时,我的应用程序首先在主要组件中路由,然后在我想要的第二组件中路由。
我想直接路由到所需的组件。
我有这个routing.ts代码:
const routes: Routes = [
{
path: 'home',
component: HomeComponent,
canActivate: [AuthGuard],
children: [
{
path: 'fp', component: FirstPageComponent
},
{
path: 'profile', component: ProfileComponent
}
]
},
{
path: 'outsidelogin',
component: outsideloginComponent,
children: [
{ path: 'login', component: LoginFirstComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'resetPasswordRequest/:id', component: ResetPassIdComponent }
]
},
{ path: '', redirectTo: '/home/fp', pathMatch: 'full' }
];
AuthGuard
canActivate(): boolean {
if (this.auth.isAuthenticated()) {
return true;
}
this.router.navigate(['/outsidelogin/login']);
return false;
}
这段代码有问题。
ngOnInit() {
if (this.auth.isAuthenticated()) {
return true;
}
handleOpenURL((appURL: AppURL) => {
console.log('Got the following appURL', appURL);
this.myappurl = appURL
let url_1 = this.myappurl.toString();
let url_id = url_1.split("/").reverse()[0];
this.resetpasss = url_id
this.router.navigateByUrl('/outsidelogin/resetPasswordRequest/' + this.resetpasss);
});
}
答案 0 :(得分:1)
使用Router Guards,为主要组件路由实现canActivate,如果您有从handleOpenURL
导航的URL,则返回false并导航到新的URL。
更新:查看代码后,我认为您必须保持ResetPassIdComponent
的轻便性。似乎它嵌套在多个页面路由器出口下,请尝试将该组件/组件副本保留在根级别,以便更好,更快地进行初始化。
将下面的代码替换为auth.guard.ts
,并从应用程序组件中删除网址处理代码。
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { LoginService } from '~/services/login';
import { handleOpenURL, AppURL } from 'nativescript-urlhandler';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private auth: LoginService) { }
canActivate(): boolean {
if (this.auth.isAuthenticated()) {
return true;
}
const timeOut = setTimeout(() => {
handleOpenURL(null);
this.router.navigate(['/test/login']);
}, 100);
handleOpenURL((appURL: AppURL) => {
if (timeOut) {
clearTimeout(timeOut);
console.log('Got the following appURL', appURL);
let url_1 = appURL.toString();
let url_id = url_1.split("/").reverse()[0];
console.log(url_id);
this.router.navigateByUrl('/test/questions/' + url_id);
}
});
return false;
}
}