简体   繁体   中英

Angular router 3 routerLink not working

I'm using Angular 2.0.0-rc3 with router 3.0.0-alpha.8.

I have a BookListComponent with the following template:

<nav>
  <a routerLink="/new-book">New Book</a>
</nav>

<ul>
  <li *ngFor="let book of books">{{ book.name }}</li>
</ul>

And then here's BookListComponent itself:

import { Component, OnInit } from '@angular/core';
import { BookService } from '../book.service';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'app-book-list',
  templateUrl: 'book-list.component.html',
  styleUrls: ['book-list.component.css'],
  providers: [ROUTER_DIRECTIVES, BookService]
})
export class BookListComponent implements OnInit {
  books: any;

  constructor(private bookService: BookService) {}

  ngOnInit() {
    this.bookService.getList()
      .subscribe(response => this.books = response.json());
  }

}

Not only does the link not take me to the /new-book route (which, if visited "manually", works just fine), but the "link" isn't even a link - it's just black text.

How can I get the link to work?

I have ROUTER_DIRECTIVES under providers but it needed to be under directives . Moving it to directives fixed the problem.

Here's my new BookListComponent :

import { Component, OnInit } from '@angular/core';
import { BookService } from '../book.service';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'app-book-list',
  templateUrl: 'book-list.component.html',
  styleUrls: ['book-list.component.css'],
  providers: [BookService],
  directives: [ROUTER_DIRECTIVES]
})
export class BookListComponent implements OnInit {
  books: any;

  constructor(private bookService: BookService) {}

  ngOnInit() {
    this.bookService.getList()
      .subscribe(response => this.books = response.json());
  }

}

Check if you are not missing the Router Outlet tag in the host's views HTML.

<router-outlet></router-outlet>

I use this as a reference:
https://angular.io/docs/ts/latest/guide/router.html

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