简体   繁体   中英

Angular Router link doesnt work

I have a navigation component with a list of elements from a webservice:

<li *ngFor="let task of tasks">
      <a routerLink="/task/{{task.id}}" ng-click="reloadRoute()"> {{task.name}}</a>
</li>

Also, in the same navigation component I have a home button:

<a routerLink="/home"><button type="button" class="btn btn-default btn-md">Go Home</button></a>

In my app.component I have just two elements, the navigation component and the router component. The router component is where i will show the /home component and the /task/id component.

<!-- static nav bar -->
<app-navigation></app-navigation>
<!-- /#page-content-wrapper -->
        <div id="page-content-wrapper">
            <div class="container-fluid">
                <router-outlet></router-outlet>
            </div>
        </div>

What happened: If I am in any task/* and then I click in the home button, it works fine. Also viceversa.
If I am in the /home and then I click into the task/1, it goes to the task. But if I am in a task/1 component, and then I click on other task/2 nothing happened. well, something happened, the URL change, but still in the task/1 page

this is my app-routing class:

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MainViewComponent } from './main-view/main-view.component';

import { ViewTaskComponent } from './view-task/view-task.component';

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: MainViewComponent },
  { path: 'task/:id', component: ViewTaskComponent }


];


@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})
export class AppRoutingModule {}

This is my Task view class:

import { Component, OnInit, Input } from '@angular/core';
import { task } from '../task';

// The HeroDetailComponent needs a new way to obtain the hero-to-display.
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';

import { TaskService } from '../task.service';


@Component({
  selector: 'app-view-task',
  templateUrl: './view-task.component.html',
  styleUrls: ['./view-task.component.css']
})
export class ViewTaskComponent implements OnInit {
    @Input() task: task;

    constructor(
// The ActivatedRoute holds information about the route to this instance of the HeroDetailComponent. 
      private route: ActivatedRoute,
// The HeroService gets task data from the remote server and this component will use it to get the task-to-display.
      private taskService: TaskService,
// The location is an Angular service for interacting with the browser. 
      private location: Location
    ) {}
// linkExtract the id route parameter
    ngOnInit(): void {
      this.getTask();
    }

    getTask(): void {
// The route.snapshot is a static image of the route information shortly after the component was created.
// The paramMap is a dictionary of route parameter values extracted from the URL. 
// The "id" key returns the id of the task to fetch.
// The JavaScript (+) operator converts the string to a number
      const id = +this.route.snapshot.paramMap.get('id');
      this.taskService.getTask(id)
        .subscribe(task => this.task = task);
    }


}

I had the same issue which I fixed with:

task component :

constructor(private route: ActivatedRoute, private http: HttpClient) {
  this.route.params.subscribe(params => {
    // whenever the url change get your task
    this.getTask(params.id);
  });
}

// getTask might something like that
getTask(id) {
  this.http.get(`baseUrl/tasks/${id}`)
    .then(task => {
      this.task = task;
    })
    .catch(err=>console.error(err));
}

it might be another solution for this, but that's the way I fixed the issue

Assuming your task structure is ok:

<li *ngFor="let task  of tasks">
  <a [routerLink]="['/task',task.id]" (click)="reloadRoute()">
     {{task.name}}
 </a>
</li>

Here is a link to the article that describes this in detail: https://angular.io/api/router/RouterLink

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