角度7导航问题-routerLink无法重定向到另一页面

时间:2020-05-21 13:24:12

标签: angular redirect routes navigation

这是我的第一个组件从节点Web api列出数据的方式。当我单击主题时,它不会重定向到下一页。

//列出所有独特的主题

@Component({
  selector: 'app-root',
  template: `<ul>
      <li *ngFor="let subject of subjects">
     <a [routerLink]="['/student/',subject.subjectId]" >{{subject.subject}}</a>
      </li>
  </ul>`,
  styleUrls: ['./app.component.css']
})
//fetch unique subjects using node api
export class AppComponent implements OnInit {
  title = 'List unique Subjects';
  subjects: any = [];

  constructor(private httpClient: HttpClient){}
  ngOnInit(){
    this.httpClient.get('http://localhost:5000/api/Subject').subscribe(data =>{


      console.log(data);
      this.subjects = data;
    })
  }
}

这是我的第二部分。它在控制台中显示错误Uncaught TypeError:无法读取未定义的属性“ innerHTML”

@Component({
  selector: 'app-student',
  templateUrl: './student.component.html',
  template: `<ul>
      <li *ngFor="let student of students">
      {{student.studentId}}
      </li>
  </ul>`,

  styleUrls: ['./student.component.css']
})

//fetch student details according to the passing subject id
export class StudentComponent implements OnInit {
    title = 'Student list';
    students: any = [];

 constructor(private httpClient: HttpClient){}
  ngOnInit(//alert(this.activeAouter.snapshot.params['id'])
  ){
    this.httpClient.get('http://localhost:5000/api/Student/ACC3TAX').subscribe(data =>{


      console.log(data);
      this.students = data;
    })
  }
}

和我的路由模块

  const routes: Routes = [
   { path: '', component: AppComponent },

{ path: '/student/:id',component: studentComponent },

    ];

3 个答案:

答案 0 :(得分:0)

我看到2个问题。

  1. 如果要在组件中使用[routerLink]="['/student...,则path: 'api/Student/:id'实际上应该是path: 'student/:id'

路由模块

const routes: Routes = [
  { path: 'home', component: StudentComponent },
  { path: 'student/:id',redirectTo: 'home', pathMatch: 'full' }
];
  1. '/student/的末尾删除正斜杠。将[routerLink]="['/student/',subject.subjectId]"替换为[routerLink]="['/student',subject.subjectId]"

组件模板

<a [routerLink]="['/student', subject?.subjectId]" >{{subject.subject}}</a>

答案 1 :(得分:0)

您可以执行以下操作

在您的routing.module.ts中,

将路径编辑为api/student/:id

在您的app.component.ts中,

删除/中多余的/student/

template: <ul>
               <li *ngFor="let subject of subjects">
                 <a [routerLink]="['api/student', subject.subjectId]" >{{subject.subject}}</a>
               </li>
          </ul>

此外,在您的student.component.ts文件中, 您正在将templateUrltemplate一起使用。您应该根据视图的复杂性使用其中之一。

答案 2 :(得分:0)

您的代码中有一些要解决的问题:

1)您不需要在角度路由中声明api端点,但是您的应用程序会路由,因此在路由器中,路径api/Student/:id应该为Student/:id(如果您甚至可以使用api前缀,想要但在这里看起来像是一个错误:))。 之后,您应该从[routerLink]="['/Student/',subject.subjectId]"

中删除前导学生/前学生

2)您在同一装饰器中使用templateUrltemplate,它们必须是唯一的,因此您必须在它们之间进行选择。

我还建议您在调试时在应用程序中启用路由器跟踪,以便获得有关路由错误的更多信息。您可以通过以下方式启用它:

imports: [
    RouterModule.forRoot(
      routes,
      { enableTracing: true } // <-- debugging purposes only
    )
]