我在Angular2以下服务:在函数angular2一个值分配给一个内部变量
@Injectable()
export class MyService{
private myServiceUrl= ....
constructor(private http: Http) { }
getService(): Promise<MyObject> {
return this.http.get(this.myServiceUrl).map(response => response.json())
.toPromise();
}
}
我在我的部件中的一个具有这样的功能:
myFunction(): any{
let toReturn: any;
this.myService.getService().then(result => toReturn = result);
console.log(toReturn);
return toReturn;
}
基本上,作为你可以看到,我想存储到返回,由myService的承诺返回的对象。我正在寻找其他人打来的电话,并且我正在获得正确的json,但是当我试图将其存储在内部变量中时,我将无法进入返回。
不过,如果我试试这个:
this.myService.getService().then(result=> console.log(result));
我能看到我想要的JSON。
我可以做这样的函数:
getService(address: string) {
this.myService.getService().then(result=> this.result= result);
}
但我宁愿让我的函数返回一个对象。我究竟做错了什么?
AFAIR地理编码API也未被zone.js覆盖,并且需要'zone.run(...)'函数中的代码在Angulars区域内运行。 –
诺言是由googleMapGeocodingService返回的,所以我没有接受Promise。 – Manuelarte
伙计们,忘了地理编码,让我们把另一个名字给服务,服务正在工作......它不工作的是分配给一个内部变量。如果我做了geocoding => console.log(地理编码),我可以看到完整的JSON。 – Manuelarte