【问题标题】:Typescript - What is the difference between an observable put request subscribe using the arrow and no arrow?Typescript - 使用箭头和不使用箭头订阅的可观察放置请求有什么区别?
【发布时间】:2020-09-19 22:57:34
【问题描述】:

如果标题措辞不当,我深表歉意。在我的 Angular 代码库中,我可以看到两个不同的 put 请求:

  public Save() {
    const types: string[] = this.getTypes.getCurrentTypes();
    this.userTypeService
      .updateTypes(this.userID, groups)
      .subscribe(() => {
        showToast("success", "User types Updated.");
      });
  }

其中 updateTypes 是一个发出简单 httpPut 请求的函数。

这个和使用的重复函数有什么区别

.subscribe( 
showToast("success", "user types updated");
)

基本上,订阅中的() => 的功能是什么?另外,有没有什么好的方法可以用这种方式从调用中捕获错误?

编辑:我想通了,下面的答案对我有用:

public Save() {
    const types: string[] = this.getTypes.getCurrentTypes();
    this.userTypeService
      .updateTypes(this.userID, groups)
      .subscribe(() => {
        result => showToast("success", "User types Updated.");
        error => showToast("error", "Error");
      });
  }

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:
    .subscribe( 
      showToast("success", "user types updated");
    )
    

    如果删除分号以修复语法错误,那么这将调用showToast立即并将返回值传递给.subscribe。这种模式有意义的唯一方法是showToast 是一个创建和返回其他函数的工厂函数,但鉴于名称我认为这不太可能。假设showToast 返回undefined,则不会创建订阅。

    简而言之:这可能是一个错误。

    您展示的第一种方法是创建函数并将该函数传递给订阅的正确方法,以便稍后调用它。

    有什么好的方法可以从调用中捕获错误

    要处理错误,您将传入第二个函数来订阅,告诉它您在错误发生时想要做什么。例如:

    .subscribe(
      (result) => {
        showToast("success", "user types updated")
      }, // <--- this function is the same as before, and handles the success case
      (error) => {
        showToast("failure", error)
      } // <--- this function is new and handles the error case.
    );
    

    【讨论】:

    • 谢谢,我想我明白了。那么,对于第一种方法,如果我想处理可能来自调用的错误,那么最好的方法是什么?抱歉,我对 Angular 很陌生 - 所以这是创建一个函数并将其传递给订阅?我以后如何调用它来执行“showtoast”?
    • observables 上的 .subscribe 允许您传入 3 个函数。第一个在 observable 成功发出值时调用,第二个在发出错误时调用,第三个在完成时调用。所以你可以通过传入第二个函数来处理错误(你的情况不需要第三个)
    • How can I call it later to get the "showtoast" to execute? 假设 updateTypes 函数是以合理的方式编写的,除了将函数传递给 subscribe 之外,您不需要做任何事情,就像您已经在做的那样。一旦 updateTypes 完成,您的函数将被自动调用。
    • 我注意到您在编辑后的回复中显示为 .subscribe( (result) (error) );而不是 .subscribe(() => {,就像你说的那样是正确的 - 我可以添加错误吗?我将编辑主要问题。
    • 你是在说我省略了大括号这一事实吗?箭头函数有一个简写,如果函数体中只有一个语句,您可以省略大括号。您仍然需要创建一个函数(或两个函数,如果您需要错误情况)。我已更新代码以删除速记。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2018-08-26
    • 2015-02-24
    • 2013-10-19
    • 1970-01-01
    • 2014-04-13
    相关资源
    最近更新 更多