Angular-Pusher服务在回击时创建多个实例,然后在浏览器中前进

时间:2018-07-17 16:43:16

标签: typescript asp.net-web-api angular5 pusher

当我在浏览器中单击“后退”按钮时,然后前进以返回到我的组件,看来推入器服务正在添加一个额外的实例,在我的情况下,它会创建重复的烤面包机通知消息。

推送服务

@Injectable()
export class PusherService {
    channel: any;
    pusher: any;

  constructor(private http: HttpClient) {
     this.pusher = new Pusher('123456', {
        cluster: 'us2',
        encrypted: true
      });
    this.channel = this.pusher.subscribe('my-channel');
   }

myComponent.ts

ngOnInit(){ 

this.pusherService.channel.bind('my-event', data => {
        this.message = true;
        if(data){ 
          this.toastr.success(data.message.NoteContent ,'Note from: ' + data.message.Author  + ' - ' + data.message.Number, {dismiss: 'click'})
          .then((toast: Toast) => {

          })

Web API

 [System.Web.Http.Route("api/Upload/CreateExternalNote")]
        [System.Web.Http.HttpPost]
        [System.Web.Http.AllowAnonymous]
        public async Task<IHttpActionResult> CreateExternalNoteAsync([FromBody]ExternalNote externalNote)
        {
           try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
              var upload = context.Upload.FirstOrDefault(x => x.UploadId == externalNote.UploadId);
              if (upload != null)
                upload.ExternalNoteReadCount = context.Upload.Where(x => x.UploadId == externalNote.UploadId)
                  .Select(x => x.ExternalNoteReadCount + 1).FirstOrDefault();
              var options = new PusherOptions
                {
                  Cluster = "us2",
                  Encrypted = true
                };

                var pusher = new Pusher(
                  "123456",
                  "asdf234234",
                  "12342sadfasd33",
                  options);
                var result = await pusher.TriggerAsync(
                  "my-channel",
                  "my-event",
                  new { message = externalNote });
              context.ExternalNote.Add(externalNote);
                context.SaveChanges();
                return Ok("Success");       
            }
            catch (Exception e)
            {          
            }     
    }

1 个答案:

答案 0 :(得分:0)

想通了,我需要在ngOnDestroy上的pusher中添加unbind to channel方法。问题是,当我使用bind方法离开组件然后返回时,创建了附加绑定。