【问题标题】:Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'details'错误:未捕获(承诺):错误:无法匹配任何路由。 URL 段:“详细信息”
【发布时间】:2020-02-13 01:39:26
【问题描述】:

我想在 Angular 应用中使用 routerLink。

app.module.ts

imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    RouterModule.forRoot([
      {
         path: 'details/:title',
        component: NewsDetailsComponent
      },
      {
        path: '',
        component: AppComponent
      }
    ])
  ],
    exports: [RouterModule]

app.component.html

    <ul>
  <li *ngFor="let article of articles"  >
    <img src="{{article.urlToImage}}">
    <a [routerLink]="['/details',article.title]">
    <h1 (click)="goToOtherComponent()" >{{article.title}}</h1>
  </a>
    <p>{{article.description}}</p>
    <p>By <span>{{article.author}}</span></p>
  </li>
</ul>

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { NewsService } from './news.service';
import { Router } from '@angular/router';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  ngOnInit() {
    this.getArticles();
  }
  constructor(public service: NewsService, private router: Router) {}

  title = 'google-news';

  articles;

  // get data from service
  getArticles() {
    this.service.getNews().subscribe(data => {
      console.log(data);
      this.articles = data['articles'];
    });
  }
  goToOtherComponent() {
    this.router.navigate(['/details']);
  }
}

我尝试了从应用程序组件到包含一些数据的新闻详细信息组件的编程导航,但我不知道我的代码有什么问题......有什么帮助吗?

【问题讨论】:

  • 你能创建 stackblitz 项目吗
  • 您的组件没有在浏览器中呈现吗?我理解的对吗?
  • @prabhatojha 我会尝试这样做
  • @ArunkumarRamasamy 是的,现在我在浏览器中看不到我的新闻详细信息组件

标签: angular angular8 angular-routing


【解决方案1】:

@R.cs

根据您的组件将呈现的路由器,您在 app.component.html 中添加 router-outlet。 将路由器插座保留在您的 app.component.html 中,而不是在您的组件中删除。

参考:https://stackblitz.com/edit/angular-6wfpnx?file=src%2Fapp%2Fapp.component.ts

【讨论】:

    猜你喜欢
    • 2017-06-16
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 2018-08-22
    • 2019-10-14
    • 1970-01-01
    • 2022-11-10
    • 2022-01-09
    相关资源
    最近更新 更多