组件未从服务接收数据 [英] Component does not receive Data from Service

查看:61
本文介绍了组件未从服务接收数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我松懈地遵循了Angular教程,并尝试从网络服务器接收数据,效果很好.但是在调用组件中,我没有收到任何数据.我仔细检查了我的代码,并与本教程进行了比较,从我的角度来看,一切都应该很好. 我没有收到任何错误,可以在控制台中看到数据,但是我没有出现在组件中.谁能解释为什么我没有收到数据?

I followed the Angular tutorial loosely and tried to receive data from a webserver, which works fine. But in the calling Component, i do not receive any data. I doublechecked my code and compared with the tutorial and from my point of view, everything should be fine. I receive no errors, can see the data in the console, but i does not appear in the component. Can anyone explain please why i do not receive the data?

这是服务功能:

getProjects(): Promise<Project[]> {

    return this.http.get(this.apiURL)
         .toPromise()
         .then(response => {
             console.log(response.json());
             response.json() as Project[]
         })
         .catch(this.handleError);
}

这是我的组件:

export class FrontpageComponent implements OnInit {

    projects: Project[] = [];

    constructor (private projectService: ProjectService) {}

    ngOnInit(): void {

        this.projectService.getProjects()
            .then(projects => {
                this.projects = projects;

                console.log(projects);
       });
    }
}

我的项目模型当前仅为:

export class Project {
    dmResponse: Object;
}

推荐答案

在您的服务,您应该返回值:

At your service, you should return the value:

     .then(response => {
         console.log(response.json());
         return response.json() as Project[];
     })

此隐式的箭头返回函数仅在语句没有大括号时才起作用.即:

This implicit return on arrow functions only works when the statement doesn't have curly braces. i.e:

     .then(response => response.json() as Project[])

这篇关于组件未从服务接收数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆