角替代订阅? [英] Angular alternative to subscribe?

查看:35
本文介绍了角替代订阅?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是异步订阅,因此在更新之前将返回计数器变量.是否有其他订阅方式可以使我仅在使用从后端获取的值更新计数器变量后才返回该计数器变量?

I'm using subscribe which is asynchronous and so the counter variable is being returned before getting updated. Is there an alternative to subscribe that will allow me to only return the counter variable once its updated with the value gotten from the backend?

makeOffer(product: string, offer: number): number {
  let formData = new FormData();
  formData.append('name', product);
  formData.append('offer', offer.toString());
  let counter = 1

  this.http.post('http://localhost/Project/PHP/negotiation.php', formData)
  .subscribe((data) => {
    counter = data['counter']
  }, (error) => {
    console.log('Error! ', error)
  });
  return counter;
}

推荐答案

您需要使用.map而不是.subscribe.以后主要用于希望将响应更新到DOM的情况.

You need to use .map instead of .subscribe. Later is mainly used if you want the response updated to the DOM.

makeOffer(product: string, offer: number): Observable<number | null> {
  let formData = new FormData();
  formData.append('name', product);
  formData.append('offer', offer.toString());
  let counter = 1

  return this.http.post('http://localhost/Project/PHP/negotiation.php', formData)
  .map((data) => {
    return data['counter']
  }, (error) => {
    console.log('Error! ', error);
    return null;
  });
}

组件:

this.service.makeOffer().subscribe((counter)=>{
     console.log(counter);
  });

这篇关于角替代订阅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆