我想按日期排序posts
数组,但首先我要查看posts
中是否有对象,帖子列表在html中正确显示但在{{1看起来console.log
。你能救我吗?
posts.component.ts
undefined
post.component.html
import { Component, OnInit } from '@angular/core';
import { Post } from '../post';
import { LoginService } from '../login.service';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { PostsService} from '../posts.service';
import { registerLocaleData } from '@angular/common';
import localeIt from '@angular/common/locales/it';
registerLocaleData(localeIt, 'it');
@Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
constructor(private loginservice: LoginService,
private location: Location,
private postsservice: PostsService) {}
posts: Post[];
postDetail(id: number){}
ngOnInit() {
this.getPosts();
console.log(this.posts);
}
getPosts(): void {
this.postsservice.getPosts()
.subscribe(posts=>this.posts=posts);
}
}
posts.service.ts
<div>
<ul>
<li *ngFor="let post of posts">
<p>{{ post.title }}</p>
<p>written by {{ post.author }} {{ post.date | date:'medium':'':''}}
<a class="details" routerLink="/detail/{{post.id}}">></a>
</p>
<br>
</li>
</ul>
</div>
答案 0 :(得分:1)
如果您想检查是否有帖子,可以使用过滤器。这样,当您订阅可观察对象时,您不需要任何逻辑。
getPosts (): Observable<Post[]> {
return this.http.get<Post[]>(this.postsUrl)
.pipe(filter(posts => posts && posts.length > 0));
}
不是在组件的订阅中对帖子进行排序,而是倾向于将逻辑保留在服务中并使用地图,例如。
getPosts (): Observable<Post[]> {
return this.http.get<Post[]>(this.postsUrl)
.pipe(
filter(posts => posts && posts.length > 0),
map(posts => sortBy(posts, ['date'])
);
}
在上面的示例中,我刚刚使用了lodash sortBy语法,但您可以使用地图中所需的任何方法返回已排序的数组。如果您在其他地方需要未分类的帖子,您可以使用单独的getSortedPosts方法,或将参数传递给getPosts(sortBy)。