Angular Material: How to display one toast after a

2020-08-15 01:08发布

问题:

I'm using $mdToast (Angular Material framework) directive to show several status messages in my Angular(-Material) web app.

When the user signs-in, if the login is successful a toast is shown by calling:

     $scope.showToastMessage = function() {
         var toast = $mdToast.simple()
             .content("Login successful);
             .action('OK')
             .highlightAction(false)
             .position($scope.getToastPosition());
          $mdToast.show(toast).then(function(toast) {
                //...
             }
         }); 
     };

After login success I need to make another check (e.g. valid session cookie) and show another toast message without overriding the previous one and after the previous one is actually showed.

The issues I get here are:

  • the second toast is shown before the new one (probably due to $mdTost's async nature)
  • this second toast is shown for less than one second and then disappears leaving on screen only the first one (basicly the second one is shown first and then hidden when the first one appears)

A solution could be either:

  • creating the second toast inside then .then callback: this doesn't work either because requires the user interventions to press the "OK" action button
  • calling $mdToast.updateContent(); (https://material.angularjs.org/#/api/material.components.toast/service/$mdToast) which would overwrite previous toast message (this is not the best solution but would be fine either) but I can't figure out how:

    (1) choose a specific toast shown on screen (let's suppose I have several toasts shown by different calls) , and

    (2) update the toast message after a delay (let's say 3 seconds) in order to show to make the user undersand that the login was successful but there is some other information.

Any clue?

回答1:

I was not sure if you wanted to show both toasts at the same time or not. If you wanted to show the sequentially you can put the second call to toast inside of the then because the action (OK) resolves the promise of the first toast. This is what I've tried:

    var toast = $mdToast.simple()
      .content('top left')
      .action('OK')
      .highlightAction(false)
      .position($scope.getToastPosition());
    var toast2 = $mdToast.simple()
      .content('Checking some other things')
      .highlightAction(false)
      .position('top left');


    $mdToast.show(toast).then(function() {
       $mdToast.show(toast2);
    });

See this CodePen.