我使用的是异步订阅,因此将在更新之前返回计数器变量。是否有其他订阅方式可以使我仅在使用从后端获取的值更新计数器变量后才返回该计数器变量?
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;
}
答案 0 :(得分:1)
您需要使用.map而不是.subscribe。以后主要用于希望将响应更新到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);
});
答案 1 :(得分:0)
不幸的是,没有。解决此问题的核心方法是从该方法返回observable,并在需要时订阅它。
答案 2 :(得分:0)
您可以尝试使用Rxjs中的map
运算符以所需的方式转换值:
对于Angular 4:
import 'rxjs/add/operator/map';
makeOffer(product: string, offer: number): Observable<number> {
...
return this.http.post('http://localhost/Project/PHP/negotiation.php', formData)
.map(data => data['counter']);
}
对于Angular 5 +
import { map } from 'rxjs/operators';
makeOffer(product: string, offer: number): Observable<number> {
...
return this.http.post('http://localhost/Project/PHP/negotiation.php', formData)
.pipe(map(data => data['counter']));
}
然后在您的组件中:
this.serviceName.makeOffer(...)
.subscribe(counter => console.log(counter));