只有在从POST获得响应后才能获取变量

时间:2018-02-27 19:58:13

标签: javascript angular typescript ionic-framework

如果我从POST请求得到响应后,如何在组件中设置变量?

component.ts代码:

formSubmit() {
    this.sent = this.submitProvider.sendByPost(this.form);
    this.formSent = this.submitProvider.formSent;
}

服务/ provider.ts:

sendByPost(form) {
    return this.http.post("http://app.api.com/mail/", form, httpOptions)
        .subscribe(
            data => (
                this.formSent = true,
            ), // success path
            error => (console.log(error)), // error path,
            () => this.formSent = true
        )
}

1 个答案:

答案 0 :(得分:1)

嗯,也许你会这样做的 您的服务

sendByPost(form) {
    return this.http.post("http://app.api.com/mail/", form, httpOptions).toPromise() // you don't need observable here
  }

然后将其订阅到组件

this.submitProvider.sendByPost(this.form).then(res => this.formSent = true)

或保持你的观察力并做同样的事情

   sendByPost(form) {
        return this.http.post("http://app.api.com/mail/", form, httpOptions) // you don't need observable here
      }

和组件

this.submitProvider.sendByPost(this.form).subscribe(res => this.formSent = true)