How to create a static method in a public class?

4

I would like to create a static method in a public class with a ToastController so that I can access this method across multiple classes. I tried to do it this way but it did not work:

export class Utils {

  constructor(public toastCtrl: ToastController) {    
  }  

  static showToast(message, pos) {
    let toast = this.toastCtrl.create({ /* <---- erro nessa linha */
      message: message,
      duration: 3000,
      position: pos
    });

    toast.onDidDismiss(() => {
      console.log('Dismissed toast');
    });

    toast.present();
  }
}

Basically the purpose reuse code. How can I create a static method in a public class?

    
asked by anonymous 08.02.2017 / 20:31

2 answers

1

The creation of the method is ok, so much so that it does not make a mistake. What is wrong is accessing this in a static method. If the method is static, it belongs to the class and not to an instance. Even if you were to access, which this should you access?

Alternatively you can send the object to the method, then you explicitly access it as a parameter. You will not be able to access the private members of the object this way, but the publics ok. If you are accessing only the audiences you can do:

export class Utils {
    constructor(public toastCtrl: ToastController) {}  

    static showToast(object, message, pos) {
        let toast = object.toastCtrl.create({
            message: message,
            duration: 3000,
            position: pos
        });
      toast.onDidDismiss(() => {
          console.log('Dismissed toast');
      });
      toast.present();
    }
}

I placed it on GitHub for future reference .

Then it will call Utils.showToast(objeto, "menssagem", 10); .

But note that this does not look like TS (although it is), the parameter types are missing. I'm not going to risk putting them on because I'm not sure what they would be.

I do not know if this would be the best solution, but I have no context.

    
08.02.2017 / 20:46
0

Since you have a dependency of ToastController , which is an Ionic service available to be injected, the correct one would be to create another service to do your message manipulation.

To accomplish this you should decorate your class with @Injectable() :

@Injectable()
export class Utils {
   //...
}

And add it to provider of your modulo or its class that will use it:

@Component({

    // ...

    // adiciona a declaração do provider aqui para que o angular (DI) saiba em qual escopo a instancia do serviço deve ser compartilhada
    // isso pode ser declarado também em modulo, onde todo o modulo irá compartilha a mesma instancia da classe injetada
    providers: [
      Utils
      ]
})
export class AppComponent {

   constructor(public utils: Utils){

   }
    // ...
}

Example:

Functional sample (Without Ionic and therefore without ToastController , using alert instead.

    
17.10.2017 / 14:16