【发布时间】: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