代码之家  ›  专栏  ›  技术社区  ›  Pierrick Martellière

“Subscription”类型的参数不能分配给“Function”类型的参数

  •  0
  • Pierrick Martellière  · 技术社区  · 6 年前

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

    函数正在工作,但它引发了一个错误:

    错误TS2345:类型为“Subscription”的参数不能分配给类型为“Function”的参数。

    以下是我的函数定义:

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

    0 回复  |  直到 6 年前
        1
  •  1
  •   Marc    6 年前

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

    附言:别忘了 unsubscribe