在Angular2中flash消息消失后​​重定向

时间:2018-04-06 12:27:12

标签: javascript angular angular2-services angular2-flashmessages

我有一个调用服务的函数。

submitPost(value:any)
{    
    this._adminLogin.postAdminLogin(this.adminLoginmodel).subscribe(
          data => {
                this.responseStatus = data;
                if(this.responseStatus.status == 1)
                {
                  localStorage.setItem('admin_id', this.responseStatus.detail.id);
                  this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: 5000 });
                  top.location.href = 'admin/dashboard';
                }
                else
                {
                  this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-danger', timeout: 2000 });
                }
              },
          err => {
                console.log(err)
              },
          () => {}
      ); 
      this.status = true;       
}

我关注的是这部分代码: -

if(this.responseStatus.status == 1)
{
    localStorage.setItem('admin_id', this.responseStatus.detail.id);
    this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: 5000 });
    top.location.href = 'admin/dashboard';
}

在5000毫秒后闪存消息消失后​​,是否有任何方法可以进行重定向操作?这样的事情: -

if(this.responseStatus.status == 1)
{
    localStorage.setItem('admin_id', this.responseStatus.detail.id);
    this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: {function(){ top.location.href = 'admin/dashboard'; }, 5000 });
}

2 个答案:

答案 0 :(得分:0)

以下代码应在消息消失后​​导航。 Yout flashMessage将显示5000毫秒,您的导航应在7000毫秒后发生

if(this.responseStatus.status == 1)
{
    localStorage.setItem('admin_id', this.responseStatus.detail.id);
    this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: 5000 });
    setTimeout(()=>{
      top.location.href = 'admin/dashboard';
    },7000);

}

答案 1 :(得分:0)

我会通过让_flashMessagesService.show()返回一个Observable来做到这一点。

在_flashMessageService中,如下所示:

myObserver : Observer<any>

function show(){
  // do stuff
  return Observable.create(observer =>{ 
     this.myObserver =observer;
  });
}

当您准备好解决Observable时,您可以执行以下操作:

this.myObserver.next('Possibly some value here');  
this.myObserver.complete();

在你的调用代码中

 this._flashMessagesService.show()
     .subscribe(result=> { top.location.href = 'admin/dashboard'});}

我一直在做类似的事情。

另一种方法可能更简单,就是在主要组件中使用Observable.timer

Observable.timer(5000).subscribe(result=> { top.location.href = 'admin/dashboard'}); 

我更喜欢第一种方式,因为它取决于flashMessage服务决定Flash消息何时消失,而不是硬编码时间值。