简体   繁体   English

角度-可观察性无法正常工作

[英]Angular - Obeservable not working correctly

I have the following code that is not working correct. 我有以下代码无法正常工作。

I have a service, which offers registration for an user. 我有一项服务,可为用户提供注册。

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);
  }

The register method is working correct, since the API where I'm registrating the users is returning "success". register方法工作正常,因为我正在向用户注册的API返回“成功”。 The problem is when I'm calling it as follows: 问题是当我按如下方式调用它时:

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

I'm also importing the necessary modules: 我还导入了必要的模块:

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

"isRegister" is remaining false and as the result the page is not redirecting to the home page. “ isRegister”保持为false,结果该页面未重定向到主页。

Does anyone have an idea where the problem could be? 有谁知道问题可能在哪里?

Thank you in advance! 先感谢您!

The isRegistered value will always be false because you are treating an asynchronous operation like a synchronous one. isRegistered值将始终为false因为您将异步操作视为同步操作。 Basically the check if (isRegistered) will run before you have acquired the value from your service. 基本上,在您从服务中获取值之前,将检查if (isRegistered)运行if (isRegistered) In order to avoid this, you have to move the checks inside of the subscription success callback: 为了避免这种情况,您必须将检查移到订阅成功回调中:

this.userService
  .register(firstname, lastname, email, password)
  .subscribe(isRegistered => {
    if (isRegistered) {
      this.router.navigate(["/home"]);
      return true;
    } else {
      return false;
    }
  });

In this way you will be sure that isRegistered 's value has been set by the result of the service call. 这样,您将确保服务调用的结果已设置isRegistered的值。

Your register() function also has a flaw - you will always return an Observable of false . 您的register()函数也有一个缺陷-您将始终返回Observablefalse You probably want to return the result of the HTTP request. 您可能想返回HTTP请求的结果。 You should .map() the result of the HTTP response to a Boolean and subscribe when using the service. 您应该将HTTP响应的结果.map()转换为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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM