angular - AppComponent.html:7 错误类型错误:_co.getPosts 不是 Object.eval 的函数 [as handleEvent]
问题描述
我是 Angular 的新手,我正在尝试使用按钮显示 API 调用的结果,认为 data.service.ts.Console 显示了这个问题:
AppComponent.html:7 错误类型错误:_co.getPosts 不是 Object.eval 的函数 [as handleEvent]
请帮忙
应用组件.ts
import { Component } from '@angular/core';
import { HttpClient} from '@angular/common/http';
import { Post } from './post';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'API';
}
App.component.html
<div style="text-align:center">
<h1>
{{ title }}!
</h1>
<div>
<button (click)="getPosts()"> Get Posts!</button>
</div>
<div>
<input type='text'(keydown)="search($event)" placeholder='search posts...'>
</div>
<div *ngFor="let post of posts">
<p><b>Title :</b> {{this.posts.title}}</p>
<p><b>Body: </b>{{this.posts.body}}</p>
</div>
<div></div>
</div>
<router-outlet></router-outlet>
数据服务.ts
import { Injectable } from '@angular/core';
import { Post } from './post';
import { Observable } from 'rxjs';
import { HttpClient} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
readonly ROOT_URL = 'https://jsonplaceholder.typicode.com';
posts: Observable<any[]>;
constructor(private http: HttpClient) {}
getPosts() {
this.posts = this.http.get<Post[]>(this.ROOT_URL + '/posts')
}
}
谢谢!!!
解决方案
getPosts() 函数是undefined
因为它没有在app.component.ts
. 相反,它只是在服务中已知,这意味着您必须constructor
像这样添加它,然后将方法添加到 app.component.ts
constructor(private dataService: DataService) {}
getPosts() {
this.dataService.getPosts()
}
但是您不会从 中返回任何值,DataService
因此它将Observable
仅保留在DataService
.
如果要显示结果,则需要从以下位置返回值DataService
数据服务.ts
getPosts() {
return this.http.get<Post[]>(this.ROOT_URL + '/posts')
}
然后你可以将它保存到某个变量中app.component.ts
getPosts() {
this.posts = this.dataService.getPosts()
}
并像这样更新您的html结构
<div *ngFor="let post of posts | async">
<p><b>Title :</b>{{post.title}}</p>
<p><b>Body: </b>{{post.body}}</p>
</div>
顺便说一句,search($event)
也调用了一些undefined
函数。
推荐阅读
- php - 如何在 Laravel 中创建和使用自定义的每日日志文件?
- sql-server - 确定远程表中新创建记录的 UniqueIdentifier id
- windows - SCOM - 单服务器域管理和代理问题
- android - 使用 Json.stringfy 在 React Native 中保存到 AsyncStorage 后如何获取 JSON.parser 值?
- android - 将应用程序移至图书馆时生成 BR 失败
- python - 如何在 Radish 测试框架中打印 step 变量?
- reactjs - 如何在选择之前增加我的图标周围的可点击区域?
- matlab - 使用迭代器访问数据时如何向量化for循环?
- ios - Swift Tableview 搜索结果单元格单击以复选标记未显示
- c# - 如何启用 Windows 脚本宿主