How to create a static method in a public class?

Asked

Viewed 1,846 times

5

I would like to create a static method in a public class with a ToastController so that I can access this method in several classes. I tried to do this way below but it didn’t 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 to reuse code. How can I create a static method in a public class?

2 answers

1

The creation of the method is ok, so much so that there is no error in it. What is wrong is to access this in a static method. If the method is static, it belongs to the class and not to an instance. Even if it were to access, which this should 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 public ok. If you are accessing only the public 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 put in the Github for future reference.

Then you’ll call Utils.showToast(objeto, "menssagem", 10);.

But note that this does not look like TS (although it is), the types of the parameters are missing. I’m not going to risk putting them on because I’m not sure which ones.

I don’t even know if this would be the best solution, but I have no context.

  • In the tsconfig.json it is possible to configure the variable noImplicitAny for false, in this case any variable without an explicit type automatically is proposed the type implicitly as any, that is, depending on the tsconfig.json that code is a valid TS.

  • @Gabrielkatakura yes, but if you are going to use TS, you should not do this, the main reason for TS is to use typing.

  • I fully agree with this, I even set the flag always to true, but I only passed on to supplement the text part não parece TS, I even think it would be interesting in the answer to talk about the flag and encourage its use in the proposed code

  • 3

    @Gabrielkatakura I only removed the ambiguity, is your comment as a complement since this is not part of the problem.

  • As a matter of fact, if that’s not TS, I don’t know what exactly TS is. I created a standard project with Cordova+ionic2+angular2 and generated the file . ts in this same format, but with the import in this way import { ToastController } from 'ionic-angular'; .. I didn’t want to add to make it more objective. Well, I tried what you did, but it hasn’t worked here yet. My question may now seem obvious, but I could not use it. This object parameter, which I should pass in another class for example?

  • @Acklay I don’t know, I don’t have enough information to say, but it’s certainly something you have toastCtrl, maybe it has to be a guy ToastController. If you had the typing, it would already be obvious. This parameter object is just what should be the this, I don’t know what it should be, nothing in this class indicates it. Understand that the this is just a hidden parameter of the method with the object being manipulated. http://answall.com/a/154195/101. I found this constructor strange in a class called Utils and who receives a ToastController.

  • @Mustache man, I’m still studying the paperwork, so I’m still taking a few tumbles. To tell the truth, I solved my problem without declaring the method as static, I’m still studying whether I did it the right way. I used the @Injectable() in my class Utils, there I declared within the @Component in another class as providers in this way: providers: [Utils]... For purposes of my need, it worked well, but I’m not sure if it’s the right way to do it. The detail is that the class did not need to be static. I will do some more tests and give you a feedback.

  • @Acklay something told me that this method wasn’t even necessary. Those specific details I don’t know. I answered about why I was making a mistake in that line and how to fix it, how far I could respond with what was posted.

  • @mustache what I did was what is on github that I’m still studying.

  • @Acklay is, so it works, I don’t know what that is Injectable So I can’t say anything, I hope it makes the class make sense, for me she’s weird in the way she is, but there must be a reason I don’t know. I don’t know Angular.

Show 5 more comments

0

How do you have a dependency on ToastController, which is an available Ionic service to be injected, the correct would be for you to create another service to do your message handling.

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

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

And add it to the provider of his modulo or his 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 example (Without Ionic and consequently without ToastController, using a alert in his stead).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.