[英]Angular redirect again to login page after successfully login
在使用nest-js
实现back-end
以使用mongo-db
进行authentication
后,当我尝试注册和登录时,我的实现工作正常,但我的问题是登录successful
后,刷新页面将我重定向到login
路线
登录成功后cookie
结果:
Authentication
expires "2022-07-29T09:48:43.000Z"
httpOnly true
path "/"
value "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MmUyOTUzMmQwZGVmYjA5NGFiMTU0YzMiLCJpYXQiOjE2NTkwODQ1MjMsImV4cCI6MTY1OTA4ODEyM30.QfMS3hI-Jpyj9CCSPgQfxHplTewSX95rl7lLTVSm-pg"
和
POST
http://localhost:4200/api/auth/login
Status
201
Created
VersionHTTP/1.1
Transferred568 B (62 B size)
Referrer Policystrict-origin-when-cross-origin
Request PriorityHighest
回复:
_id "62e29532d0defb094ab154c3"
email "test@gmail.com"
app.module.ts
@NgModule({
declarations: [
AppComponent,
HomeComponent,
NotFoundComponent,
],
imports: [
CommonModule,
BrowserModule,
GraphQLModule,
HttpClientModule,
HomeComponent,
LoginModule,
SignUpModule,
AppRoutingModule,
],
providers:
[{
provide: APOLLO_OPTIONS,
useFactory: (httpLink: HttpLink) => {
return {
cache: new InMemoryCache(),
link: httpLink.create({
uri: '^api/graphql' //using proxy
})
}
},
deps:[HttpLink]
}],
bootstrap: [AppComponent]
})
export class AppModule {
}
auth.guard.ts
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(
private readonly authService: AuthService,
private readonly router: Router) {
}
canActivate() {
return this.authService.isAuthenticated().pipe(
tap((authenticated)=>{
if(!authenticated){
console.log('you should login')
this.router.navigate(['login']);
}
})
)
}
}
app.component.ts
@Component({
selector: 'front-root',
templateUrl: './front.component.html',
styleUrls: ['./front.component.css']
})
export class FrontComponent implements OnInit {
isLoggedIn$: Observable<boolean>;
constructor(
private readonly authService: AuthService,
private readonly router: Router
) {
this.isLoggedIn$ = authService.authenticated$;
}
ngOnInit(): void {
}
}
auth.service.ts
@Injectable(
{
providedIn: 'root'
}
)
export class AuthService {
private readonly authenticated = new Subject<boolean>();
authenticated$ = this.authenticated.asObservable();
constructor(private readonly httpClient: HttpClient) {}
isAuthenticated() {
return this.httpClient.get<boolean>('api/auth/login').pipe(
tap(() => {
this.authenticated.next(true);
}),
catchError(() => of(false)));
}
}
front-routing.module.ts
const routes: Routes = [
{path: '', component: HomeComponent, pathMatch: 'full'},
{
path: 'news', loadChildren: () => import('./pages/news/news.module').then(n => n.NewsModule)
},
{
path: 'teachers',
loadChildren: () => import('./pages/teachers/teachers.module').then(n => n.TeachersModule),
canActivate: [AuthGuard]
},
{path: 'not-found', component: NotFoundComponent},
{path: '**', redirectTo: 'not-found'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class FrontRoutingModule {
}
顺便说一句,在打开teachers
路线时,我收到此消息和错误:
XHR GET http://localhost:4200/api/auth/login
[HTTP/1.1 404 Not Found 4ms]
you should login
但是这个模块将我重定向到登录页面。
`proxy.conf.json`
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"pathRewrite": {
"^/api": ""
},
"logLevel": "debug"
}
}
angular.json
"configurations": {
"production": {
"browserTarget": "front-end:build:production" ,
"proxyConfig": "src/proxy.conf.json"
},
"development": {
"browserTarget": "front-end:build:development",
"proxyConfig": "src/proxy.conf.json"
}
},
订阅您的事件/服务,当您获得正确的数据时,您应该将令牌保存在某处,然后使用Router
导航您在组件中看不到的页面。
也许阅读 Angular 文档将帮助您更多地了解此路由:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.