简体   繁体   English

我在组件 Angular 8 中调用服务未定义

[英]I get undefined from calling a service in a component Angular 8

I have created an interface and a service in which this service is responsible for getting some data from API but when I try to call that from a component, it returns undefined to me.我创建了一个接口和一个服务,其中该服务负责从 API 获取一些数据,但是当我尝试从组件调用它时,它返回 undefined 给我。 these are my services and my component (I have also noticed that the function within the service returns void and I have provided them in app.module )这些是我的服务和我的组件(我还注意到服务中的函数返回 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()})}
}

and this is my component:这是我的组件:

import { TasksService } from '../../services/tasks.service';
export class DoneTaskItemsComponent implements OnInit {
constructor(private tasksService:TasksService){}

ngOnInit() {
    console.log(this.tasksService.getCompeletedTasks())}
}

I have just deleted things like @component and other things for more readable of codes我刚刚删除了诸如@component 之类的内容,以便更易读地阅读代码

So any solution for that?那么有什么解决方案吗? I need to use the compeletedTasks on the template but for now, when I log them on the console, I get undefined我需要在模板上使用 compeletedTasks 但现在,当我在控制台上登录它们时,我得到了未定义

As @Challappan says you need to use httpClient instead of http for making api requests.正如@Challappan 所说,您需要使用 httpClient 而不是 http 来发出 api 请求。

Try to change code like below.尝试更改如下代码。

getCompeletedTasks(){
   return this.http.get("http://localhost:4000/api/compeleted");
}

In component like below.在如下组件中。

compeletedTasks: Task[]

ngOnInit() {
    this.tasksService.getCompeletedTasks().subscribe(response => {
         this.completedTasks = response;
    });
}

This link might help.此链接可能会有所帮助。

angular httpClient api example medium angular httpClient api 示例中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM