【发布时间】:2019-03-16 01:21:27
【问题描述】:
我对 Angular 很陌生,目前我正在学习 Angular 6,它是 Angular 的最新版本。
在这里,我正在尝试使用从 JSON 检索的文章来设计我的博客页面,并将它们显示在 2 列中,如下图所示:
标题旁边的数字是文章数组中文章的索引。很容易看出问题:从 1 开始的索引重复了两次。
这是我的代码,请详细说明为什么我错了以及如何解决。
博客服务:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class BlogService {
constructor(private http: HttpClient) { }
getArticleList() {
return this.http.get('https://jsonplaceholder.typicode.com/posts');
}
}
文章列表组件:
从'@angular/core'导入{组件,OnInit}; 从'../blog.service'导入{ BlogService };
@Component({
selector: 'app-blog',
templateUrl: './article-list.component.html',
styleUrls: ['./article-list.component.css']
})
export class ArticleListComponent implements OnInit {
articles: Object;
constructor(private data: BlogService) { }
ngOnInit() {
this.data.getArticleList().subscribe(
data => this.articles = data
);
}
}
HTML 文件:
<div class="article-list-page">
<div class="container">
<h3>This is blog page</h3>
<p>The industry's top wizards, doctors, and other experts offer their best advice, research, how-tos,
and insights, all in the name of helping you level-up your SEO and online marketing skills. Looking for the YouMoz Blog? </p>
<span *ngFor="let index of articles; index as i">
<div style="display: table; border: 1px solid black">
<div class="posts-left col-md-6" style="display: table-row;">
<a>{{ articles[i].title }} -- {{i}}</a>
<p>{{ articles[i].body }}</p>
</div>
<div class="posts-right col-md-6" style="display: table-row;">
<a>{{ articles[i + 1].title }} -- {{i + 1}}</a>
<p>{{ articles[i + 1].body }}</p>
</div>
</div>
</span>
</div>
</div>
【问题讨论】:
-
如果你想显示所有文章,你不需要做{{articles[i].title }}...你应该做{{articles.title }}只有它们列出...而不是索引...您还可以显示 {{articles.id}}... 这是您数据中的 ID 字段