我正在使用服务从json服务器检索数据,但是,当在服务内部创建console.log()
时,控制台会向我显示从json检索的数据,但是当我尝试将其提取出来时服务中出现以下错误:
load-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>
答案 0 :(得分:2)
如下所述更改您的服务方法并订阅您的组件,
getTarefasInternas(): any {
return this.http.get(`${API}/getTarefasInternas`)
)}
和组件
ngOnInit() {
this.homeService.getTarefasInternas().subscribe((data)=>{
this.tarefasInternas = data;
});
}