在Ionic中,为什么路由在iPhone上不起作用,但在构建版本和ion服务上工作



我有一个应用程序(顺便说一下,它与node.js服务器通信(,在离子和路由和登录页面适用于ionic serve版本,但无法作为iPhone应用程序运行。问题是我可以在iPhone上运行该应用程序并查看登录页面,但是当我设置正确的凭据并按OK时,我不会路由到下一页(这是用户登录时的默认页面(,所以我不知道错误在哪里。我试图在index.htmlbase href="/"base href="."的情况下构建应用程序,但这不起作用。我还能尝试什么?这是 app.module.ts 中定义路由模块的代码:

import { AppRoutingModule } from './app-routing.module';

然后它也有导入部分:

imports: [
BrowserModule,
AppRoutingModule, 
SharedModule,
],

接下来,这是 ap-routeting.module 中的相关代码:

import { Routes, RouterModule } from "@angular/router";
import { AuthGuard } from "./services/auth.guard";
const routes: Routes = [
{
path: "streams",
loadChildren: "./components/streams/streams.module#StreamsModule",
canActivate: [AuthGuard]
},

流模块相关代码:

import { StreamsRoutingModule } from './streams-routing.module';
import { SharedModule } from './../../shared/shared.module';
@NgModule({
declarations: [StreamsComponent],
imports: [
CommonModule,
SharedModule,
StreamsRoutingModule
]
})

这是登录时触发的代码:

loginUser() {
this.showSpinner = true;
this.authService.loginUser(this.loginForm.value).subscribe(
data => {
this.tokenService.SetToken(data.token);
this.loginForm.reset();
setTimeout(() => {
this.router.navigate(["streams"]);
}, 3000);
},
err => {
this.showSpinner = false;
if (err.error.message) {
this.errorMessage = err.error.message;
}
}
);
}

最后,流路由模块中的 routes 变量:

const routes: Routes = [
{
path: "",
component: StreamsComponent
},
{
path: "streams",
component: StreamsComponent
},
{
path: "**",
redirectTo: "streams",
pathMatch: "full"
}
];

这是身份验证:

import { Injectable } from "@angular/core";
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router";
import { Observable } from "rxjs";
import { TokenService } from "./token.service";
@Injectable({
providedIn: "root"
})
export class AuthGuard implements CanActivate {
constructor(private router: Router, private tokenService: TokenService) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
const token = this.tokenService.GetToken();
if (token) {
return true;
} else {
this.router.navigate(["/"]);
return false;
}
}
}

现在,在ios应用程序的登录过程中,在使用safari开发人员模式进行检查时,我可以看到来自iPhone上应用程序的http流量,并且我可以看到正在拨打电话并检索到正确的响应,即我已登录,但是,屏幕冻结在登录页面上。为什么路由在ios应用程序上无法正常工作,而在ionic server版本上工作正常?

事实证明,问题出在AuthGuard服务上。守卫返回布尔结果。如果用户已登录,则返回 true 并继续导航。

授权守卫是原因,我通过返回 true 来简化它, 它传递路由现在工作。

我很高兴我能够帮助您提出解决方案。


附言此外,如果您想在用户无权的情况下阻止应用程序加载整个模块,您可以使用canLoad().例如:

canLoad() {
return this._storage.get('userLogged').then(res => {
if (res) {
this.router.navigate(['/example-route']);
return false;
} else {
return true;
}
});
}

最新更新