angular 不同组件间通过service传递数据

Posted on 2020-10-29 17:15  !sylar  阅读(618)  评论(0编辑  收藏  举报

//global.service.ts

import { Injectable } from "@angular/core"
import { Subject } from "rxjs"
interface globalModalModel {
  tipMsg?: string
  show?: boolean
  duration?: number
}
@Injectable({
  providedIn: "root"
})
export class GlobalService {
  constructor() {}
  private globalModal = new Subject<any>()
  globalModal$ = this.globalModal.asObservable()
  updateGlobalModal(data: globalModalModel) {
    this.globalModal.next(data)
  }

  public sysTime
  public globalTime = new Subject<any>()
  globalTime$ = this.globalTime.asObservable()
  updateGlobalTime(data: any) {
    this.globalTime.next(data)
    this.sysTime = data
  }
}

监听数据变化:

 this.subscription_globalModal = this.GlobalService.globalModal$.subscribe(
      (data) => {
        this.tipMsg = data.tipMsg || ""
        this.globalMaskShow = data.show
        setTimeout(() => {
          this.globalMaskShow = false
        }, data.duration || 3000)
      }
    )

 

更新数据:

 this.GlobalService.updateGlobalModal({
            show: true,
            duration: 1000000,
            tipMsg: "服务器连接中断, 正在尝试重新连接....."
          })