Angular 8 Http Post从订阅获取布尔值

如何解决Angular 8 Http Post从订阅获取布尔值

我尝试从布尔值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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-