问题描述
我尝试从布尔值true / false的 subscribe 中获取价值,但是我无法获取价值,这是我到目前为止使用的内容。
我的http帖子的旧方法。
this.http.post(HostedpathConst.Hostedpath + `CompanyProfile/UpdateCustomeRSStatus`,fData)
.subscribe(data => this.Success(data),err => this.Error(err));
this.Success(data)
和this.Error(err)
是现在被调用的方法,我尝试获取数据的新方法是这样。
const fData = new FormData();
fData.append('Id',Id.toString());
fData.append('IsActive',IsActive.toString());
const test = this.http.post(HostedpathConst.Hostedpath + `CompanyProfile/UpdateCustomeRSStatus`,fData)
.subscribe(data => {
this.Success(data);
this.Switch = IsActive;
return this.Switch;
},err => {
this.Error(err);
this.Switch = !IsActive;
return this.Switch;
});
console.log(test);//Subscriber {closed: false,_parentOrParents: null,_subscriptions: Array(1),syncErrorValue: null,syncErrorThrown: false, …}
console.log(this.Switch);//undefined at first then gives opposite result like true gives false and vice versa
作为this.Switch = IsActive;
的布尔值以获取数据,它首先返回 undefined ,然后在病房之后返回值 false 而不是 true ,反之亦然。
解决方法
因为我了解您的问题是由于异步内容,所以我将在此处写一个说明。简单地说,您不知道异步操作何时结束。例如,当您执行http函数时,您正在与服务器通信,因此您不知道服务器何时响应(由于连接速度慢,通信量大,或者可能是因为您要求繁重的操作)。 / p>
为解决此问题,我们使用了使用观察者模式的subscribe()方法。因此,这里的要点是因为您不知道服务器或操作(如线程)何时完成,因此您订阅了该服务器并一直在观察任何更改或答案。收到该消息后,将执行订阅中的代码。
您可以在此处了解有关观察者模式的更多信息:https://en.wikipedia.org/wiki/Observer_pattern#:~:text=The%20observer%20pattern%20is%20a,calling%20one%20of%20their%20methods。 和异步理论在这里:https://en.wikipedia.org/wiki/Asynchrony_(computer_programming)
对于您的问题,您可以将值初始化为false,并将复选框值设置为[(ngModel)] =“ Switch”,以便在更新开关变量时,复选框也将更新!
,由于其可观察,因此您不会立即得到响应。因此控制台记录此内容。在成功和错误块内切换。尝试以下代码段
const fData = new FormData();
fData.append('Id',Id.toString());
fData.append('IsActive',IsActive.toString());
const test = this.http.post(HostedPathConst.HostedPath + `CompanyProfile/UpdateCustomersStatus`,fData)
.subscribe(data => {
this.Success(data);
this.Switch = IsActive;
console.log("Success",this.Switch);
return this.Switch;
},err => {
this.Error(err);
this.Switch = !IsActive;
console.log("Error",this.Switch);
return this.Switch;
});
我不确定这是否可以解决您的问题,但是绝对可以通过调试来获取解决方案。
注意:您得到undefined at first then gives opposite result like true gives false and vice versa
的原因是,您在成功或错误块之外安慰this.Switch
,这在大多数情况下都会首先返回undefined,接下来分配值。由于this.Switch是全局作用域变量。
使用def parse_competitor_product_page(self,response):
# Function that scrapes information from a product page and yields the competitor
# only if it actually matches our search.
' Do some work and scrape required product attributes'
competitor = ProductItem()
competitor['product'] = prod_name
competitor['asin'] = asin
competitor['Title'] = title
competitor['producer'] = producer
competitor['MainImage'] = image
competitor['Rating'] = rating
competitor['NumberOfReviews'] = number_of_reviews
competitor['price'] = price
competitor['AvailableSizes'] = sizes
competitor['AvailableColors'] = colors
competitor['Varieties'] = varieties
competitor['BulletPoints'] = bullet_points
competitor['SellerRank'] = seller_rank
variaton = self.is_right_product(prod,competitor):
if variation is True or variation is None:
# send to Scarpy's Engine: ProductItem without changes
yield competitor
else:
# send to Scarpy's Engine: Request to page with variation
yield self.update_product_to_right_variation(competitor,variation)
def is_right_product(self,product,competitor):
# Function that checks whether a resulting competitor actually matches the product that
# we looked for. It returns a boolean if it does. It also alters some attributes of that
# competitor if a right variation is found on its page.
'''I will omit some if else branches as those work well and I will only post the faulty
branch (which happens to be the one that should modify the competitor object because
a right variation is found on its page. '''
if product_is_right_quantity(competitor):
return True # it will assing `True` to `variaton = ...` in `parse_competitor_product_page()`
# it will assing `variation` or `None` to `variaton = ...` in `parse_competitor_product_page()`
return find_variation_of_right_quantity(product['quantity'],competitor)
def update_product_to_right_variation(self,competitor,variation_asin):
print("IN UPDATE PRODUCT TO RIGHT VARIATION")
variation_asin = response.xpath(f'//div[@id="variation_color_name"]/ul/li[contains(@title,\'{variation_name}\')]/@data-defaultasin').get()
product_url = f"https://www.amazon.it/dp/{variation_asin}"
print(product_url)
# send back to `parse_competitor_product_page()`
return scrapy.Request(url=product_url,callback=self.update_competitor_from_product_page,errback=self.errback_http,meta={'prod':competitor,'asin':variation_asin})
def update_competitor_from_product_page(self,response):
print("INSIIDE UPDATE COMPETITOR FROM PRODUCT PAGE")
prod = response.meta['prod']
asin = response.meta['asin']
price = response.xpath('//*[@id="priceblock_ourprice"]/text()').extract_first()
#title = ...
prod['price'] = price
prod['Title'] = title
prod['asin'] = asin
#response.meta['prod'] = prod # useless
print(prod['price'])
# send to Scarpy's Engine: item with changes
yield prod
和async
来获得结果并且有效。
await