Kar*_*sai 8 typescript angular
我在Angular 2中跟随Http put请求:
...
...
private Url='api/demo/'
UpdatState(obj: Model) {
let headers = new Headers({
'Content-Type': 'application/json',
});
return this.http.put(this.Url + obj.Id, JSON.stringify(obj), { headers: headers }).map(res => res.json().data).subscribe(..);
}
Run Code Online (Sandbox Code Playgroud)
和相同型号的获取服务:
getState(){
return this.http.get(this.Url)
.map(response => response.json());
}
Run Code Online (Sandbox Code Playgroud)
问题:我以这样的方式设置我的组件,即首先发出请求 - 这会在Db中更改我的表.紧接着,获取获取表条目的请求.但是,在Put请求完成之前,get完成其执行.
...
...
onSomeEvent(){
this.updatestate(obj);
this.getState();
}
...
...
Run Code Online (Sandbox Code Playgroud)
如何检测我的http请求是否在Angular 2中完成?
编辑:从@Gunter的答案,我提供了三个回调到我的订阅方法:
UpdatState(obj: Model) {
let headers = new Headers({
Content-Type': 'application/json',
});
return this.http.put(this.Url + obj.Id, JSON.stringify(obj), { headers: headers })
.map(res => res.json().data)
.subscribe(
(a) => { this.b = a }, //b is my local array
err => { this.error = err; }, //error is my local string variable
() => { this.completed(); }
);
}
Run Code Online (Sandbox Code Playgroud)
我完成的方法是:
completed(){
alert("Request completed");
}
Run Code Online (Sandbox Code Playgroud)
你可以传递三个回调 subscribe(...)
this.http.put(...).subscribe(
value => this.doSomething(value), // called for each value
error => this.handleError(err),
() => this.completed()
})
Run Code Online (Sandbox Code Playgroud)
当observable关闭时调用最后一个.因为http.xxx()
总是只发出一个值然后关闭observable,所以第一个和最后一个几乎是相同的.
还有一个finally()
被称为在任何情况下(成功和错误)运算符.