订阅方法在 MEAN 堆栈应用程序中不起作用

问题描述 投票:0回答:1

我已经为我的应用程序创建了一个后端,现在正在开发前端。我正在尝试执行我的应用程序的注册组件。

这是我的注册组件,我试图注册用户。 我遇到的问题是,当调用 OnRegisterSubmit 方法时,实际上创建了用户并将其写入数据库,但其他代码不起作用,但我认为 .subscribe() 方法无法正常工作

export class RegisterComponent implements OnInit {

  username: String | null = null;
  password: String | null = null;
  firstname: String | null = null;
  lastname: String | null = null;

  constructor(private validateService: ValidateService,
              private authService: AuthService,
              private router: Router
          ){}

  ngOnInit(){}

  onRegisterSubmit(){
    const user = {
      username: this.username,
      password: this.password,
      firstname: this.firstname,
      lastname: this.lastname
    }

    if(!this.validateService.validateRegister(user)){
        alert('Please fill in all fields');
        return;
    }

   //Register User
   this.authService.registerUser(user).subscribe(data => {
    if((data as any).success ) {
      // Registration was successful
      alert('You are now registered');
      this.router.navigate(['/login']);
    } else {
      // Registration failed
      alert('Something went wrong');
      this.router.navigate(['/register']);
    }
  });

  return null;
  
  }
}

这是我的auth.service:

interface User {
  username: String | null;
  password: String | null;
  firstname: String | null;
  lastname: String | null;
}

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

  authToken: any;

  constructor(private httpClient: HttpClient) { }

  registerUser(user: User) {
    const headers = new HttpHeaders().set('Content-Type', 'application/json');
    return this.httpClient.post('https://localhost:3000/api/users/signup', user, { headers });
  }
  
}

最后是我的用户路线:

// Create new user
router.post('/signup', async(req,res) => {
    const {error} = validateUser(req.body);
    if (error) return res.status(400).json(error.details[0].message);

    const isUnique = (await User.count({username: req.body.username})) === 0;
    if(!isUnique)
    return res
.status(401)
.json({error: 'The username or password is not valid'});
try{
    const user = new User(req.body);
    user.password=await hashPassword(user.password);
    await user.save();
} catch(err) {
    return res.status(500).json(err);
}
res.status(200);
})

如果有人知道为什么会发生这种情况,我将不胜感激。谢谢你。

如果您确实需要更多信息,请随时询问。

javascript angular typescript mean-stack
1个回答
0
投票

试试这个:

.subscribe({
    next: (v) => console.log(v),
    error: (e) => console.error(e),
    complete: () => console.info('complete') 
})
© www.soinside.com 2019 - 2024. All rights reserved.