1
我创建了以下组件,它是一个小型演示,因此我在此处使用服务而不是创建单独的服务。如何在angular2中正确使用http服务?
export class AppComponent {
@Input() takeInput:string;
@Output() result;
constructor(private http: Http) { };
public onSubmit(value: any){
this.takeInput = value;
this.getAll(value.url); //below console.log prints first then the one prints which is written inside this getAll method.
console.log("this prints first", this.result); //returns undefined
//How do I use this.result here which gets set once getAll() execution is finished.
}
这里是调用服务,并获取数据的方法:
private getAll (url){
return this.http.get(url)
.map((res: Response) => res.json())
.subscribe((res: Object) => {
this.result = res;
console.log("this prints second",this.result); // returns proper response
});
}
}
如何可以等待观察到的返回数据,然后使用这些数据在我的调用方法的onsubmit()或任何其他方式继续使用this.result作为其他方法的参数执行。
但仍ASYC代码执行连续和我this.result =未定义在下一行。 'public onSubmit(value:any){ this.takeInput = value.takeInput; ()返回数据 console.log(this.result); //返回数据 }); } public otherMethod(this.result)=> {0} {console.log(this.result)//在数据从服务中获取之前运行,因此undefined } ' –
对不起!在我的代码中有拼写错误...我更新了我的答案。 –
你可以看看,我简化了这个问题,专注于痛点。 –