Component does not receive Data from Service

2020-02-15 05:37发布

问题:

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?

This is the service function:

getProjects(): Promise<Project[]> {

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

and this my component:

export class FrontpageComponent implements OnInit {

    projects: Project[] = [];

    constructor (private projectService: ProjectService) {}

    ngOnInit(): void {

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

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

My project Model currently is just:

export class Project {
    dmResponse: Object;
}

回答1:

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[])


标签: angular