Я хочу отсортировать по дате массив posts
, но сначала я хочу посмотреть, есть ли объекты в posts
, список сообщений корректно отображается в html, но в console.log
он выглядит undefined
. ты можешь мне помочь?
posts.component.ts
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);
}
}
post.component.html
<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>
posts.service.ts
import { Injectable } from '@angular/core';
import { Post } from './post';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { HttpClient, HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class PostsService {
private postsUrl = 'api/posts'; // URL to web api
posts = [];
constructor(private http: HttpClient) { }
/** GET posts from the server */
getPosts (): Observable<Post[]> {
return this.http.get<Post[]>(this.postsUrl)
}
getPost(id: number): Observable<Post> {
const url = `${this.postsUrl}/${id}`;
return this.http.get<Post>(url);
}
/** PUT: update the post on the server */
updatePost (post: Post): Observable<any> {
return this.http.put(this.postsUrl, post, httpOptions);
}
/** POST: add a new post to the server */
addPost (post: Post): Observable<Post> {
return this.http.post<Post>(this.postsUrl, post, httpOptions);
}
/** DELETE: delete the post from the server */
deletePost (post: Post | number): Observable<Post> {
const id = typeof post === 'number' ? post : post.id;
const url = `${this.postsUrl}/${id}`;
return this.http.delete<Post>(url, httpOptions);
}
}