猿问

使用箭头和不使用箭头的可观察放置请求订阅有什么区别?

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


  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");

      });

  }


慕盖茨4494581
浏览 108回答 1
1回答

牧羊人nacy

.subscribe(&nbsp;&nbsp; showToast("success", "user types updated");)如果删除分号以修复语法错误,那么这将showToast 立即调用并将返回值传递给.subscribe. 这种模式唯一有意义的方式是 ifshowToast是一个创建并返回其他函数的工厂函数,但鉴于名称,我认为这不太可能。假设showToast返回undefined,将不会创建订阅。简而言之:这可能是一个错误。您展示的第一种方法是创建函数并将该函数传递给订阅的正确方法,以便稍后调用它。有什么好的方法可以从调用中捕获错误要处理错误,您将传递第二个函数进行订阅,告诉它发生错误时您想做什么。例如:.subscribe(&nbsp; (result) => {&nbsp; &nbsp; showToast("success", "user types updated")&nbsp; }, // <--- this function is the same as before, and handles the success case&nbsp; (error) => {&nbsp; &nbsp; showToast("failure", error)&nbsp; } // <--- this function is new and handles the error case.);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答