首页 > 解决方案 > 在订阅方法函数之外获取变量数据

问题描述

我想创建一个从使用外部 API 的服务返回对象的函数。我无法让它工作。

GetMatchinfo (matchid : number  ) : Match {

    let aq :Match;

    this.matchService.GetMatch(matchid).subscribe(
        (Matchinfodata: Match)=>{     
            aq=Matchinfodata;
         }
    ); 

    return aq;

}

标签: angular

解决方案


如果您从模板调用函数,只需将返回调用的位置移动到订阅块。或者如果你正在使用GetMatchInfo()内部的一些其他功能,最好使用 observable 和 subject。

GetMatchInfo (matchid : number  ) : Observable<Match> {

    let aq = new Subject<Match>();

    this.matchService.GetMatch(matchid).subscribe(
        (Matchinfodata: Match)=>{     
            aq.next(Matchinfodata);
         }
    ); 

    return aq.asObservable();

}

并订阅GetMatchInfo()您需要的功能。

this.GetMatchInfo(id).subscribe(
    (result) => {
        console.log(result)
    }
);

推荐阅读