property subscribe does not exist on type 'void'
10,299
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)))
);
}
posts.component.ts
ngOnInit() {
this.postsService.getPosts().subscribe(posts => {
this.posts = posts;
});
}
or you can use 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>
Related videos on Youtube
Author by
James Macharia
Updated on June 04, 2022Comments
-
James Macharia almost 2 years
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); }); } }
-
Dince12 over 5 yearsPlease show this.newsService.getData(), guessing you are returning void on that function which is not what you want. you will need to use and Observable rather than void.
-
-
James Macharia over 5 yearskindly explain how to implement "observable", because am just a beginner learning the angular and ionic coding world
-
Dmitry Grinko almost 5 years@JamesMacharia Don't forget to unsubscribe. It's very important.