[英]I get undefined from calling a service in a component Angular 8
我創建了一個接口和一個服務,其中該服務負責從 API 獲取一些數據,但是當我嘗試從組件調用它時,它返回 undefined 給我。 這些是我的服務和我的組件(我還注意到服務中的函數返回 void 並且我在 app.module 中提供了它們)
@Injectable()
export class TasksService {
compeletedTasks: Task[]
constructor(public http: Http) { }
getCompeletedTasks(){
this.http.get("http://localhost:4000/api/compeleted").subscribe(response =>{
this.compeletedTasks = response.json()
return response.json()})}
}
這是我的組件:
import { TasksService } from '../../services/tasks.service';
export class DoneTaskItemsComponent implements OnInit {
constructor(private tasksService:TasksService){}
ngOnInit() {
console.log(this.tasksService.getCompeletedTasks())}
}
我剛剛刪除了諸如@component 之類的內容,以便更易讀地閱讀代碼
那么有什么解決方案嗎? 我需要在模板上使用 compeletedTasks 但現在,當我在控制台上登錄它們時,我得到了未定義
正如@Challappan 所說,您需要使用 httpClient 而不是 http 來發出 api 請求。
嘗試更改如下代碼。
getCompeletedTasks(){
return this.http.get("http://localhost:4000/api/compeleted");
}
在如下組件中。
compeletedTasks: Task[]
ngOnInit() {
this.tasksService.getCompeletedTasks().subscribe(response => {
this.completedTasks = response;
});
}
此鏈接可能會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.