Как получить объект из Observable?
Проект Angular а-ля новостной портал.
export class CategoriesService {
constructor(private http: HttpClient) {
}
getCategories(): Observable<any> {
return this.http.get('./assets/categories.json');
}
getCategory(id: number | string): Observable<Category> {
return this.getCategories()
.pipe(
map((categories: Array<Category>) => categories.find(category => category.id === +id)),
catchError(err => Observable.throw('Error in getCategory method'))
);
}
}
Сервис читает локальный categories.json содержащий массив объектов Category и возвращает Observable.
[
{
"id": 1,
"title": "Science",
"description": "Posts for the most curious ones..",
"url": "science",
"backgroundImageURL": "/images/2019/07/photo-617a33825bc6.jpeg"
},
....
Компонент NewsList получает список новостей из NewsService и отображает. У каждой новости Article есть categoryId: number. Я в шаблоне хочу получить значение поля title для передаваемого categoryId.
<p>{{getCategory(article.categoryId)}}</p>
Компонент NewsList:
export class NewsListComponent implements OnInit {
news$: Observable<Array<Article>>;
constructor(private newsService: NewsService,
private categoriesService: CategoriesService) {
}
ngOnInit() {
this.news$ = this.newsService.getNews();
}
getCategory(categoryId: number | string):string {
return this.categoriesService.getCategory(categoryId);
}
}
Подскажите, пожалуйста, как в
getCategory(categoryId: number | string):string {
return this.categoriesService.getCategory(categoryId);
}
получить поле title? Пробовал так:
getCategory(categoryId: number | string) {
return this.categoriesService.getCategory(categoryId).pipe(map(cat => cat.title));
}
И так:
getCategory(categoryId: number | string) {
let category;
this.categoriesService.getCategory(categoryId).pipe(map(c => category = c.title));
return category;
}
К сожалению, не работает.