Я использую JSONPlaceholder, из которого я хочу читать и отображать все сообщения по одному. Когда я нажимаю на заголовок поста, он должен перейти на страницу с подробностями этого поста. Я также создал stackblitz . Нажмите на Все сообщения на панели навигации. Позвольте мне объяснить мой код здесь.
post.service.ts
import { ...} from '@angular/core';
...
@Injectable({
providedIn: 'root'
})
export class PostService {
private postsUrl = '/posts';
constructor(private httpClient: HttpClient) {}
// fetch all posts
getAllPosts():Observable<Post[]> {
return this.httpClient.get<Post[]>('https://jsonplaceholder.typicode.com/posts');
}
//fetch specific post
getPostByID(id: number): Observable<Post> {
console.log("getPostByID called");
const url = `${this.postsUrl}/${id}`;
return this.httpClient.get<Post>(url)
.pipe(
tap(data => console.log('getPost: ' + JSON.stringify(data)))
);
}
}
post-details.component.ts
import { Component } from '@angular/core';
...
@Component({
templateUrl: './post-details.component.html',
})
export class PostDetails {
errorMessage="";
post: Post;
pageTitle = 'Product Detail';
constructor(private route: ActivatedRoute, private postService: PostService) {
}
getPost(id: number) {
console.log("getPost called");
this.postService.getPostByID(id).subscribe({
next: post => {
this.onPostRetrieved(post);
},
error: err => this.errorMessage = err
});
}
ngOnInit() {
const id=+this.route.snapshot.paramMap.get('id');
console.log(id);
this.getPost(id);
}
onPostRetrieved(post: Post): void {
this.post = post;
console.log("onPostRetrieved called");
if (this.post) {
this.pageTitle = `Product Detail: ${this.post.title}`;
} else {
this.pageTitle = 'No product found';
}
}
}
Там нет ошибки, но я не получаю детали. И консоль также выглядит хорошо, см .:
Я заметил, что управление не идет внутрь onPostRetrieved () . Я проверил решение, но я не могу это исправить. Пожалуйста, поправьте меня.