Search code examples
angulartypescriptcallbacksubscription

Argument of type 'Subscription' is not assignable to parameter of type 'Function'


I'm new to Angular and actually trying to define a function with a piped callback in parameter.

The function is working but it throws an error:

error TS2345: Argument of type 'Subscription' is not assignable to parameter of type 'Function'. Type 'Subscription' is missing the following properties from type 'Function': apply, call, bind, prototype, and 5 more.

Here's my function definition:

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

And I'm calling this function as this:

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

What am I doing wrong please ?

Thank for your help.


Solution

  • Try this:

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

    P.S.: Don't forget to unsubscribe