Angular 如何从另一个组件中的方法返回值?
我有component details.ts,其中我有这个方法:Angular 如何从另一个组件中的方法返回值?,angular,Angular,我有component details.ts,其中我有这个方法: getCantonsByCode(cantonCode: string) { this.restService.getSelectedByCode("rcanton", cantonCode) .subscribe(results => { return this.canton = results["payload"]; }); } 在component address.t
getCantonsByCode(cantonCode: string) {
this.restService.getSelectedByCode("rcanton", cantonCode)
.subscribe(results => {
return this.canton = results["payload"];
});
}
在component address.ts中,我想做如下操作:
this.addressDetailForm.addressDetails.viewAttr2 = this.addressDetailForm.getCantonsByCode(address.cantonCode)
但是我没有定义。任何关于如何返回该值的建议?您应该做的第一件事是将代码更改为以下内容:
getCantonsByCode(cantonCode: string) {
this.restService.getSelectedByCode("rcanton", cantonCode)
.subscribe(results => {
this.canton = results["payload"];
return this.canton;
});
}
getCantonsByCode(cantonCode: string) {
this.restService.getSelectedByCode("rcanton", cantonCode)
.map(results => results["payload"]);
}
然而,如果这不能解决您的问题,您应该确保结果是否真的符合您的期望
编辑
我同意另一个答案,即您不应该通过服务的属性访问数据,因此我将改进我的答案。您应该执行以下操作:
getCantonsByCode(cantonCode: string) {
this.restService.getSelectedByCode("rcanton", cantonCode)
.subscribe(results => {
this.canton = results["payload"];
return this.canton;
});
}
getCantonsByCode(cantonCode: string) {
this.restService.getSelectedByCode("rcanton", cantonCode)
.map(results => results["payload"]);
}
并订阅组件中的可观察内容。如果address.ts
是details.ts
的父级,则可以使用
将您的getCantonsByCode
公开为public
方法
在您的address.html
和地址
@ViewChild('details') details : DetailsComponent
details.getCantonsByCode(address)
编辑:我误解了
未定义的原因是您的方法正在进行异步调用
此行不返回任何内容
this.addressDetailForm.addressDetails.viewAttr2 = this.addressDetailForm.getCantonsByCode(address.cantonCode)
您必须将方法更改为以下内容
getCantonsByCode(cantonCode: string) : Observable<any>{
return this.restService.getSelectedByCode("rcanton", cantonCode)
}
地址组件应该像细节组件一样直接通过服务访问数据。一般来说,组件之间不应该相互了解,尤其是在访问数据时。
通过其他组件(UI层)访问数据(服务层)是没有意义的。当我在getCantonsByCode中执行console.log this.canton时,我获取数据,但在其他组件中,当我执行console.log时,我获取未定义的数据。如果我在address.ts中移动我的函数,并且我不需要ViewChild,当我执行console.log时,我再次获取未定义的数据(此.getCantonByCode(address.cantonCode))很抱歉,我误解了您的问题,您意识到您得到未定义的原因是因为您的方法没有同步返回?您在订阅之外没有返回当我将其放入订阅时,我也得到未定义,但在console.log inside subscribe中我得到data@None检查我的编辑,你误解了n同步和异步代码。