Angular:返回订阅结果

时间:2018-05-04 07:32:19

标签: angular api exception

我在IProject上收到错误 must return a value

我想从api返回结果。

public getProjectDetails(projectId: number): IProject {
        this.testStationService.getProjectById(projectId)
            .subscribe(
                (res) => {
                    return res;
                });
    }

2 个答案:

答案 0 :(得分:0)

您还必须返回您的服务方法

return this.testStationService.getProjectById(projectId)

答案 1 :(得分:0)

您正在尝试同步返回异步Observable的值。因此,当getProjectById发出一个值时,函数getProjectDetails已经完成并且什么也没有返回。

您必须返回Observable本身并在需要其值的地方订阅它,或者甚至更好地使用async-pipe - > https://angular.io/api/common/AsyncPipe

所以getProjectDetails看起来像这样:

public getProjectDetails(projectId: number): Observable<IProject> {
    return this.testStationService.getProjectById(projectId);
}