【问题标题】:I get undefined from calling a service in a component Angular 8我在组件 Angular 8 中调用服务时未定义
【发布时间】:2020-04-28 16:48:42
【问题描述】:

我创建了一个接口和一个服务,该服务负责从 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 但现在,当我在控制台上记录它们时,我得到 undefined

【问题讨论】:

  • 您在 getCompeletedTasks(compeletedTasks) 方法中定义了争论,但是在调用时您没有传递任何参数????尝试在 getCompeletedTasks 方法中 console.log 并检查它是否正在安慰??
  • 您使用的是哪个版本的 Angular?
  • 试试@Injectable({ providedIn: 'root' })
  • 你没有定义,因为你没有从函数返回任何东西
  • 请检查发布的答案。你需要返回 observable 然后在组件中订阅它。

标签: angular typescript service dependency-injection


【解决方案1】:

正如@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;
    });
}

此链接可能会有所帮助。

angular httpClient api example medium

【讨论】:

  • 这是我在组件属性“订阅”中得到的,在“订阅”类型上不存在。您的意思是“取消订阅”吗?此处声明了“取消订阅”。
  • 谢谢,我只是想出了如何处理上面的评论,谢谢你的帮助
猜你喜欢
  • 2020-11-27
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
  • 2019-12-19
  • 1970-01-01
  • 2018-09-02
  • 2020-01-26
  • 1970-01-01
相关资源
最近更新 更多