简体   繁体   中英

Angular routing bug - this.router.navigateByUrl() and this.router.navigate()

I am creating angular application that will handle documentation for my GitHub apps, in more complex way than just readme files. I want to redirect user after clicking in topnav dropdown to selected route, but there's problem with router. (I need to redirect with some parameters, but it doesn't work even with simple path reditect). Those methods redirect to target route for like 1 seconds (like excepted), then user got redirected back to root page.

Code:

  /* First element is project name, second is category/part of application name */
  choices = ["typing_speed_test", "overview"]
  json = json

  constructor(private router: Router){}

  onProjectClick($event){
    this.choices[0] = $event.target.innerHTML.trim();
    this.choices[1] = "overview";
    this.redirect();
  }

  onCategoryClick($event){
    this.choices[1] = $event.target.innerHTML.trim();
    this.redirect();
  }

  redirect(){
    this.router.navigateByUrl("404");
  }

Routes:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'project/:project_name/:category', component: SubpageComponent },
    { path: '404', component: NotFoundComponent },
    //{ path: '**', redirectTo: '404', pathMatch: 'full' }
];

Link to gif with problem: https://imgur.com/a/x2mPxvh Full code in github repo: https://github.com/Dolidodzik/DocsForMyApps (if you used code from here to answer this question, please point that in your answer)

I think I may did some stupid mistake, because I am pretty new in Angular, but I couldn't do it, because every google question showed me solves for ERRORS, when redirect doesn't work at all, not to bugs like in my situation.

You need to remove the href="#" from your anchor links in your navigation bar. It's causing the browser to reload:

<a class="dropdown-item" *ngFor="let item of categories() | keyvalue">
  {{item.key}}
</a>

Also this is a bit weird solution:

this.choices[0] = $event.target.innerHTML.trim();

You better just send the item variable in your function call in your template, and you can then read this in your component event handler:

onProjectClick(item){
  this.choices[0] = item.key;
  this.choices[1] = "overview";
  this.redirect();
}

the problem is your lins look like this:

 <a href="#" (click)="navigateInsideApp(routeX)">link</a>

default link behavior causes your app reload from the start. you should use [routerLink]="['someUrl']" instead of href . If you need that href in some cases, consider calling $event.preventDefault() to cancel the native browser navigation

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