Javascript 来自服务的数据请求不起作用
我正在使用服务从json服务器检索数据,但是,当我在服务内部创建一个Javascript 来自服务的数据请求不起作用,javascript,angular,typescript,ionic-framework,Javascript,Angular,Typescript,Ionic Framework,我正在使用服务从json服务器检索数据,但是,当我在服务内部创建一个console.log()时,控制台会向我显示从json检索到的数据,但是当我尝试从服务中获取数据时,会出现以下错误: 装载服务 import { Injectable } from '@angular/core'; import { API } from '../../app.api' import { HttpClient } from '@angular/common/http' @Injectable() ex
console.log()
时,控制台会向我显示从json检索到的数据,但是当我尝试从服务中获取数据时,会出现以下错误:
装载服务
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>
{{tarefa.descripcao}}
{{tarefa.inicio}}-{{tarefa.fim}
{{tarefa.comentario}}
当我调用控制台.log
退出服务时:
如下图所示更改您的服务方法,并在您的组件中订阅
getTarefasInternas(): any {
return this.http.get(`${API}/getTarefasInternas`)
)}
和在组件中
ngOnInit() {
this.homeService.getTarefasInternas().subscribe((data)=>{
this.tarefasInternas = data;
});
}
按如下所示更改您的服务方法,并在组件中订阅
getTarefasInternas(): any {
return this.http.get(`${API}/getTarefasInternas`)
)}
和在组件中
ngOnInit() {
this.homeService.getTarefasInternas().subscribe((data)=>{
this.tarefasInternas = data;
});
}
谢谢,它很管用!但我应该何时以及如何取消订阅此服务?使用管道异步解决了这个问题?你仍然可以在组件中自己做对不起,但我不明白。例如,当我更改页面时,是否取消订阅?我想防止备忘录泄漏您不需要取消订阅HttpClient observables:谢谢,它可以工作!但我应该何时以及如何取消订阅此服务?使用管道异步解决了这个问题?你仍然可以在组件中自己做对不起,但我不明白。例如,当我更改页面时,是否取消订阅?我想防止备忘录泄漏您不需要取消订阅HttpClient Observable: