Angular2 - 在函数后更新变量(promise?)

时间:2016-01-16 15:53:11

标签: asynchronous promise wait angular

我有一些问题。在我的注册中,如果用户已存在于数据库中,我想查看错误消息。所以我创建了" serverAnswer"变量,它将处理来自服务器的错误答案。

我的register.service.ts内容

@Injectable()
export class RegisterService {
  constructor(private http: Http) {}

  public serverAnswer: Object;

  getAnswer() {
    return this.serverAnswer;
  }

  addUser(user: User) {
    var headers = new Headers();
    headers.append('Content-type', 'application/json');

    this.http.post('/users/register', JSON.stringify(user), {headers: headers})
    .subscribe(
      response => {
        if(response.json().success) {
          window.location.href = "/";
        }
        if(response.json().error) {
          this.serverAnswer = response.json();
        }
      }
    )
  }
}

正如您所看到的,在开始时服务器响应"变量是空的。 " response.json()。错误"处理我的错误文本。好的,现在是时候展示我的register.component.ts内容了。

export class RegisterComponent {
  constructor(private http: Http, private registerService: RegisterService) {}

  serverAnswer: Object;

  onSubmit(userName: string, userPassword: string, userEmail: string) {
    this.registerService.addUser(new User(userName, userPassword, userEmail))
    this.serverAnswer = this.registerService.getAnswer();
  }
}

问题在于" systemAnswer"来自RegisterService的功能已在addUser函数完成之前更新。结果是,如果这个用户已经存在于数据库中,那么第一次就是" systemAnswer"是空的,第二次处理response.json()。错误文本。

这个地方:

this.registerService.addUser(new User(userName, userPassword, userEmail))
this.serverAnswer = this.registerService.getAnswer();

只有在addUser函数完成后才能更新serverAnswer变量?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

如果从服务中返回Observable对象会更好:

@Injectable()
export class RegisterService {
  constructor(private http: Http) {}

  addUser(user: User) {
    var headers = new Headers();
    headers.append('Content-type', 'application/json');

    return this.http.post('/users/register', JSON.stringify(user), {headers: headers})
        .map(response => response.json());
  }
}

然后在控制器中使用它:

export class RegisterComponent {
    constructor(private http: Http, private registerService: RegisterService) {}

    serverAnswer: Object;

    onSubmit(userName: string, userPassword: string, userEmail: string) {
        this.registerService.addUser(new User(userName, userPassword, userEmail))
            .subscribe(
                response => {
                    if (response.success) {
                        window.location.href = "/";
                    } else if (response.error) {
                        this.serverAnswer = response;
                    }
                }
            );
    }
}