首页 > 解决方案 > 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')
 }
}

谢谢!!!

标签: angular

解决方案


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函数。


推荐阅读