【问题标题】:Argument of type 'Subscription' is not assignable to parameter of type 'Function'“订阅”类型的参数不可分配给“功能”类型的参数
【发布时间】:2020-09-08 08:48:09
【问题描述】:

我是 Angular 的新手,实际上试图在参数中定义一个带有管道回调的函数。

该函数正在运行,但它会引发错误:

错误 TS2345:“订阅”类型的参数不可分配给“功能”类型的参数。 “订阅”类型缺少“功能”类型的以下属性:应用、调用、绑定、原型等等。

这是我的函数定义:

checkNetworkThenExecute(callback: Function) {
      Network.getStatus().then((status) => {
        if (status.connected) {
          callback();
        } else {
          if (this.networkHandler == null) {
            this.networkHandler = Network.addListener(
              "networkStatusChange",
              (status) => {
                if (status.connected) {
                  this.networkHandler.remove();

                  callback();
                }
              }
            );
          }
          alert("Merci de vous connecter à un réseau.");
        }
      });
    }

    searchWord(query: string) {
      const url = "https://api.mapbox.com/geocoding/v5/mapbox.places/";
      return this.http
        .get(
          url +
            query +
            ".json?types=address&access_token=" +
            environment.mapbox.accessToken
        )
        .pipe(
          map((res: MapboxOutput) => {
            return res.features;
          })
        );
    }

我将这个函数称为:

this.mapboxService.checkNetworkThenExecute(
          this.mapboxService
            .searchWord(searchTerm)
            .subscribe((features: Feature[]) => {
              this.addresses = features.map((feat) => feat.place_name);
              console.log(this.addresses);
            })
        );

请问我做错了什么?

感谢您的帮助。

【问题讨论】:

    标签: angular typescript callback subscription


    【解决方案1】:

    试试这个:

    this.mapboxService.checkNetworkThenExecute( () => {
          this.mapboxService
            .searchWord(searchTerm)
            .subscribe((features: Feature[]) => {
              this.addresses = features.map((feat) => feat.place_name);
              console.log(this.addresses);
            });
           }
        );
    

    P.S.:别忘了unsubscribe

    【讨论】:

    • 您好,感谢您的回答。我知道订阅可能会造成内存泄漏,但在我的示例中不明白如何做到这一点。你能根据我的代码给我一个例子吗?再次感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    相关资源
    最近更新 更多