我有以下代码无效。
我有一项服务,为用户提供注册。
register(firstname: string, lastname: string, email: string, password: string): Observable<boolean> {
let body = {firstname: firstname, lastname: lastname, email: email, password: password};
this.http.post(this.base_url + "api/register/user/", body)
.subscribe(
(data) => {
if((data as any).status == 'success') {
return Observable.of(true);
}
},
(error) => {
return Observable.of(false);
});
return Observable.of(false);
}
注册方法工作正常,因为我注册用户的API正在返回&#34;成功&#34;。问题是当我按如下方式调用它时:
registerUser(e) {
...
let isRegistered = false;
this.userService.register(firstname, lastname, email, password).subscribe(register => isRegistered = register);
if(isRegistered) {
console.log("isRegistered = true");
this.router.navigate(['/home']);
return true;
} else {
console.log("isRegistered = false");
return false;
}
}
我还要导入必要的模块:
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
&#34; isRegister&#34;保持不变,因此页面不会重定向到主页。
有没有人知道问题出在哪里?
提前谢谢!
答案 0 :(得分:6)
false
值始终为if (isRegistered)
,因为您正在处理异步操作,如同步操作。基本上,检查this.userService
.register(firstname, lastname, email, password)
.subscribe(isRegistered => {
if (isRegistered) {
this.router.navigate(["/home"]);
return true;
} else {
return false;
}
});
将在您从服务中获取值之前运行。为了避免这种情况,您必须在订阅成功回调中移动支票:
isRegistered
通过这种方式,您可以确保服务电话的结果已设置register()
的值。
您的Observable
函数也有缺陷 - 您将始终返回false
.map()
。您可能希望返回HTTP请求的结果。您应该Boolean
对register(firstname: string, lastname: string, email: string, password: string): Observable<boolean> {
const body = { firstname, lastname, email, password };
return this.http.post(this.base_url + 'api/register/user/', body)
.map(data => {
if((data as any).status === 'success') {
return Observable.of(true);
} else {
return Observable.of(false);
}
})
.catch(() => Observable.of(false));
}
的HTTP响应的结果,并在使用该服务时进行订阅。
$(function () {
// Calls when checkbox is checked.
$('[id*=GridView1] [id*=GridView1_chkRow]').on('click', function () {
if ($(this).is(":checked")) {
//Second Gridview.
var gridview2 = $('[id*=gvSelected]');
//Get Row Which Checbox is Selected.
var tr = $(this).closest('tr');
//Ignoring the checkbox column so that it wont get added in second gridview.
var tds = $(tr).find('td').not('.IgnoreCheckBoxColumn');
var row = '<tr>';
for (var i = 0; i < tds.length; i++) {
row += tds[i].outerHTML;
}
row += '</tr>';
//Appending selected row to second gridview.
gridview2.append(row);
}