2016-08-11 26 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

你可以看看,我簡化了這個問題,專注於痛點。 –

相關問題