如何在angular2中正确地使用http服务

How to properly consume http service in angular2?

本文关键字:http 服务 正确地 angular2      更新时间:2023-09-26

我已经创建了下面的组件,这是一个小的演示,所以我在这里使用服务,而不是创建一个单独的服务。

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.
    }

下面是调用service和获取数据的方法:

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()中使用该数据或任何其他方式继续执行。结果作为其他方法的参数

你可以像这样重构你的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);
  });
}