微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我没有在 Angular11 中成功注册和登录用户后使用 router.navigate() 重定向?

如何解决为什么我没有在 Angular11 中成功注册和登录用户后使用 router.navigate() 重定向?

这个问题可能看起来很长,但对我来说真的很重要。我成功地能够在 firebase 中注册一个新用户,但没有重定向到“/chatroomlist”路径。我尝试了所有可能的方法,请帮助我!!

app.module.ts

import { AuthGuardService } from './auth-guard.service';
import { RouterModule } from '@angular/router';
import { environment } from './../environments/environment';
import { NgModule } from '@angular/core';
import { AngularFireModule } from '@angular/fire';
import { browserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { AngularFireDatabaseModule } from '@angular/fire/database';
import { RegisterComponent } from './register/register.component'
import { AuthService } from './auth.service';
import { LoginComponent } from './login/login.component';
import { ChatroomlistComponent } from './chatroomlist/chatroomlist.component';

@NgModule({
  declarations: [
    AppComponent,RegisterComponent,LoginComponent,ChatroomlistComponent
  ],imports: [
    browserModule,AppRoutingModule,AngularFireModule.initializeApp(environment.firebase),AngularFireAuthModule,AngularFireDatabaseModule,RouterModule.forRoot([
      { path: '',component: RegisterComponent },{ path: 'login',component: LoginComponent },{ path: 'register',{ path: 'chatroomlist',component: ChatroomlistComponent,canActivate: [AuthGuardService] }
    ])
  ],providers: [
    AuthService,AuthGuardService
  ],bootstrap: [AppComponent]
})
export class AppModule { }

auth.service.ts

import { AngularFireAuth } from '@angular/fire/auth';
import { Injectable } from '@angular/core';
import { ActivatedRoute,Router } from '@angular/router';
import { Observable } from 'rxjs';
import * as firebase from 'firebase';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(private afAuth: AngularFireAuth,private router: Router,private route: ActivatedRoute) { }

  register(email: any,password: any){
    return firebase.default.auth().createuserWithEmailAndPassword(email,password)
      .then(() => {
        this.router.navigate(['chatroomlist']); // here,.then() never works. It is not redirected
      }).catch((error) => {
        console.log(error);
      })
  }

  login(email: any,password: any){
    return firebase.default.auth().signInWithEmailAndPassword(email,password)
      .then(() => {
        
        this.router.navigate(['chatroomlist']);  //this path is also not getting redirected. I tried ['/chatroomlist'] too. but it's not working
      }).catch((error) => 
        console.log(error)
      )
  }
}

register.component.ts

import { AuthService } from './../auth.service';
import { AngularFireAuth } from '@angular/fire/auth';
import { Component } from '@angular/core';

@Component({
  selector: 'register',templateUrl: './register.component.html',styleUrls: ['./register.component.css']
})
export class RegisterComponent  {

  constructor(private authService: AuthService) { }

  register(email: any,password: any){
    this.authService.register(email,password);
  }
}

登录.component.ts

import { AuthService } from './../auth.service';
import { Component } from '@angular/core';

@Component({
  selector: 'app-login',templateUrl: './login.component.html',styleUrls: ['./login.component.css']
})
export class LoginComponent {

  constructor(public authService: AuthService) { }

  login(email: any,password: any) {
    this.authService.login(email,password);
  }
}

register.component.html

<div class="container">
<h2>Registration</h2><br>
<form>
    <div class="form-group">
        <label for="inputEmail">Email address</label>
        <input  #email type="email" class="form-control" aria-describedby="emailHelp" placeholder="Enter email" required>
    </div>
    <div class="form-group">
        <label for="inputPassword">Password</label>
        <input #password type="password" class="form-control" placeholder="Password" required>
    </div>
    <div>
        <button type="submit" class="btn btn-primary" (click)="register(email.value,password.value)">Register</button><br>
        <a routerLink="/login">Already a user? Please Login here!</a>
    </div>
</form>
</div>

login.component.html

<div class="container">
    <h2>Login</h2><br>
    <form>
        <div class="form-group">
            <label for="inputEmail">Email address</label>
            <input  #email type="email" class="form-control" aria-describedby="emailHelp" placeholder="Enter email" required>
        </div>
        <div class="form-group">
            <label for="inputPassword">Password</label>
            <input #password type="password" class="form-control" placeholder="Password" required>
        </div>
        <div>
            <button type="submit" class="btn btn-primary" (click)="login(email.value,password.value)">Login</button><br>
            <a routerLink="/register">New user? Register here!</a>
        </div>
    </form>
    </div>

解决方法

尝试在服务的组件中使用 router.navigate,因为组件是您在路由器中使用的:

RouterModule.forRoot([
      { path: '',component: RegisterComponent },{ path: 'login',component: LoginComponent },{ path: 'register',{ path: 'chatroomlist',component: ChatroomlistComponent,canActivate: [AuthGuardService] }
    ])

所以现在尝试从服务返回一个承诺:

register(email:string,password:string){
    return new Promise((resolve,rejected)=> {
      this.AngularAuth.auth.createUserWithEmailAndPassword(email,password).then(user => {
        resolve(user)
      }).catch(err => rejected(err));
    });
  }

在寄存器组件中:

register(email: any,password: any){
    this.authService.register(email,password).then(this.router.navigate(['chatroomlist']));
  }

记得在构造函数中添加路由器

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?