javascript - 来自服务的数据请求不起作用

标签 javascript angular typescript ionic-framework

我正在使用服务从 json 服务器检索数据,但是,当我在服务内部创建一个 console.log() 时,控制台会向我显示从 json 检索的数据,但是当我尝试退出服务时,出现以下错误:

enter image description here

加载home.service

import { Injectable } from '@angular/core';

import { API } from '../../app.api'

import { HttpClient } from '@angular/common/http'

@Injectable()

export class LoadHomeService {

  constructor(private http: HttpClient) { 

  }

  getTarefasInternas(): any {
    return this.http.get(`${API}/getTarefasInternas`)
      .subscribe((response) =>{
        console.log (response) // it works
      } 
  )}

  getTarefasExternas(): any {
    return this.http.get(`${API}/home`)
      .subscribe((response) =>{}
  )}
}

home.page.ts

import { Component } from '@angular/core';
import { LoadHomeService } from './load-home.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage  {
  tarefasInternas : any
  constructor(private homeService: LoadHomeService) { }

  ngOnInit() {
    this.tarefasInternas = this.homeService.getTarefasInternas()

  }
}

HTML 标记:

<ion-list>
    <ion-item *ngFor="let tarefa of tarefasInternas" class="in-list item ion-focusable item-label hydrated">
      <ion-label class="sc-ion-label-ios-h sc-ion-label-ios-s hydrated">
        <h2>{{tarefa.descricao}}</h2>
        <h3>{{tarefa.inicio}} - {{tarefa.fim}}</h3>
        <p>{{tarefa.comentario}}</p>
      </ion-label>
    </ion-item>
  </ion-list>

当我从服务中调用 console.log 时: enter image description here

最佳答案

如下更改您的服务方法并在您的组件中订阅,

getTarefasInternas(): any {
    return this.http.get(`${API}/getTarefasInternas`)
)}

以及组件中

ngOnInit() {
this.homeService.getTarefasInternas().subscribe((data)=>{
    this.tarefasInternas = data;
});
}

关于javascript - 来自服务的数据请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54994391/

相关文章:

javascript - 使元素可见并在单击时隐藏

javascript - NodeJS + Websockets + HTML5 视频标签和 'streaming'

javascript - 如何从一个 svg 中的路径元素链接到另一个 svg 的不同元素

angular - 在 Angular 模板中访问联合类型的属性

angular - 参数类型 {path : string, component HomeComponent}[] 不可分配给参数类型 Routes

typescript - 如何在 Typescript 中编写严格要求其参数的函数类型

reactjs - React.HTMLProps<> 和 React.HTMLAttributes<T> 有什么区别?

javascript - 如何从JS中的对象数组中提取和附加对象

angular - 使用 Material2 MdAutocomplete 组件 - 如何使用 onselect 事件

RouteConfigLoadEnd-Handler 中的 Angular 访问 route._loadedConfig