简体   繁体   中英

router navigate not working inside a subscribe (angular)

I'm facing the following problem:

Im call my getByUsernameandPassword method and I recieve a response, but when I try to redirect the user to the /zeiterfassung route it just shows me the same /login page.. I wrote a console.log() to check if its entering in the res, and it does.. can someone please tell me what I am doing wrong?

Component:

  public async anmelden() {
    this.loading = true;
    this._benutzerservice.getByUsernameAndPassword(this.benutzerFormControl.value, this.passwortFormControl.value)pipe(first()).subscribe(
      res =>  {
        this._router.navigate(['/zeiterfassung']);
      },
      err => {
        console.log("a");
      });

Try routing outside the subscription,

public async anmelden() {
    this.loading = true;
    this._benutzerservice.getByUsernameAndPassword(this.benutzerFormControl.value, this.passwortFormControl.value) pipe(first()).subscribe(
        res => {
            this.redirect('/zeiterfassung');
        },
        err => {
            console.log("a");
        });
}

redirect(path) {
     this.router.navigate([path]) 
}

by default navigate method will try to navigate to yourdomain.com/zeiterfassung
by following way it will navigate to current URL eg yourcurenturl/zeiterfassung

import { ActivatedRoute } from '@angular/router';

constructor(private route :ActivatedRoute) 

public async anmelden() {
    this.loading = true;
    this._benutzerservice.getByUsernameAndPassword(this.benutzerFormControl.value, this.passwortFormControl.value)pipe(first()).subscribe(
      res =>  {
        this._router.navigate(['zeiterfassung'],{relativeTo:this.route});
      },
      err => {
        console.log("a");
      });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM