如何在angular2中正确地使用http服务
How to properly consume http service in angular2?
我已经创建了下面的组件,这是一个小的演示,所以我在这里使用服务,而不是创建一个单独的服务。
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);
});
}
相关文章:
- $http服务未触发成功或错误回调
- Http服务工厂将未定义的返回到Angular中的控制器
- 在http服务单元测试中使用request-js时,chai.request不是一个函数
- Angular $http 服务不加载 json 文件
- 在 angularJs 中从控制器调用同时$http服务
- Angular 中的 HTTP 服务将 POST 数据作为请求正文的键发送,没有值
- AngularJS$http服务中的encodeURIComponent
- 从服务器获取数据,并使用$http服务和ng-change在select事件上显示它
- 如何在AngularJS中动态更改$http服务URL
- 如何在Angular中设置异步HTTP服务的回调,以便在不定义数组的情况下在控制器中填充数组
- Angular-使用httpBackend测试http服务会引发意外异常
- 如何在有角度的$http服务请求中将JSONP指定为dataType
- 使用$http服务将数据发布到本地 json 文件时未发现错误
- ES6 发电机与$http服务
- Angular JS:在HTTP服务(POST)中传递输入参数
- 使用 angular 的 $http 服务来调用 js 文件
- AngularJS - 将then()与$http服务一起使用
- AngularJS$http服务中的调用,返回解析的数据,而不是承诺
- 如果可能的话,我应该使用 angularjs $http服务来处理请求还是 jquery ajax
- 如何将异常从 PHP 抛出到 Angular $http 服务