Issue
I am having an constant error that tends to pop up in my code (using Visual Studio Code as my IDE):
Property subscribe does not exist on type 'void'.....
When I run the code, I get an error message in Ionic localhost.
import { Component, OnInit } from '@angular/core';
import { NewsService } from '../news.service';
@Component({
selector: 'app-news',
templateUrl: './news.page.html',
styleUrls: ['./news.page.scss'],
})
export class NewsPage implements OnInit {
constructor(private newsService: NewsService) { }
ngOnInit() {
this.newsService.getData('everything?q=bitcoin&from=2018-10-09&sortBy=publishedAt')
.subscribe(data => {
console.log(data);
});
}
}
Solution
The method should return observable to have opportunity subscribe on it.
This is an example how to use Observable:
models/post.ts
export interface IPost {
id: number;
title: string;
}
export class Post implements IPost {
id: number;
title: string;
constructor(postData: any) {
this.id = postData.id;
this.title = postData.title;
}
}
posts.service.ts
getPosts(): Observable<Post[]> {
const url = 'https://jsonplaceholder.typicode.com/posts';
return this.httpClient.get<Post[]>(url)
.pipe(
map(response => response.map(postData => new Post(postData)))
);
}
Usage. Option 1:
posts.component.ts
ngOnInit() {
this.postsService.getPosts().subscribe(posts => {
this.posts = posts;
});
}
posts.component.html
<ul *ngIf="posts">
<li *ngFor="let post of posts">
<span>{{post.title}}</span>
</li>
</ul>
Usage. Option 2. Using an async pipe:
posts.component.ts
postsObservable: Observable<Post[]>;
ngOnInit() {
this.postsObservable = this.postsService.getPosts();
}
posts.component.html
<ul *ngIf="postsObservable | async; let posts">
<li *ngFor="let post of posts">
<span>{{post.title}}</span>
</li>
</ul>
Answered By - Dmitry Grinko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.