我遇到一个经常发生的错误,该错误往往会在我的代码中弹出(使用Visual Studio Code作为我的IDE):
类型为'void'的属性订阅不存在.....
运行代码时,我在Ionic本地主机中收到一条错误消息。
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);
});
}
}
答案 0 :(得分:2)
该方法应该返回observable,以便有机会订阅它。
这是一个如何使用Observable的示例:
模型/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;
});
}
或者您可以使用异步管道:
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>