2016-08-11 25 views
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作为其他方法的参数执行。

回答

1

你可以重构你的getAll方法这样搬出认购上相应的观察到:

private getAll(){ 
    let url = "https://something"; 
    return this.http.get(url) 
    .map((res: Response) => res.json()); 
    } 
} 

,并使用它像这样:

public onSubmit(value: any){ 
    this.takeInput = value.takeInput; 
    this.getAll().subscribe(result => { 
    console.log(result); 
    this.result = result; 
    console.log(this.result); 
    }); 
} 
+0

但仍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 } ' –

+0

对不起!在我的代码中有拼写错误...我更新了我的答案。 –

+0

你可以看看,我简化了这个问题,专注于痛点。 –

相关问题