监听事件时推送数组

Push on an array when listening to an event

我正在使用 Ionic,我想在发出事件时推送一个对象数组。

我有这个

    export  class PublicationService {

    constructor(
        private storage: Storage
    ){}

    private addPublicationSubject = new BehaviorSubject<PublicationModel>(new PublicationModel());
    data = this.addPublicationSubject.asObservable();

    publishData(data: PublicationModel) {
        this.addPublicationSubject.next(data);
    }
   }

这里,事件被发出

    savePublication() {
    this.newPublication.id_pub = 1;
    this.newPublication.textPub = this.f.text.value;
    this.newPublication.user_sender = 'Juance';
    this.newPublication.datetime = "asd";
    this.pubService.publishData(this.newPublication);
  }

在我的主页上事件是监听(在 ngOnInit 中)

// Variable defined in the component
publications: PublicationModel[] = [];

//ngOnInit
this.pubService.data.subscribe((data) => {
      if (data != null) {
        console.log(data);

        this.publications.push(data);
      }
});

现在我的问题是:当我尝试将数据推入数组时,它告诉我它无法读取 属性 of null (this.publications)。

在进入事件的订阅时,并没有像组件中定义的那样取变量。有什么想法吗?

编辑:

我的组件首页

    @Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss']
})
export class HomePage implements OnInit {

  viewAddPublication: boolean;
  publications: PublicationModel[] = [];
  countLikePub:   number;
  addPublication: any;

  constructor(
    private storage: Storage,
    private navCtrl: NavController,
    private pubService: PublicationService) {
      this.publications = new Array<PublicationModel>();
  }

  ngOnInit() {
    this.publications = [];

    this.pubService.data.subscribe((data) => {
      if (data != null) {
        console.log(data);

        this.setData(data);
      }
    }
    );
    this.viewAddPublication = false;
    this.countLikePub = 0;

    this.storage.get('publications').then((val) => {
      this.publications = val;
    });

  }

  setData(data) {
    this.publications.push(data);
  }

  goToAddPub() {
    this.navCtrl.navigateForward('/add-publication', {
      animated: true,
      animationDirection: "forward",

    });
  }

  public likedPost(event) {
    console.log();
    let like = (document.getElementById(event.target.id) as HTMLElement);
    like.style.color = '#0277bd';
    this.countLikePub++;
  }

chrome

中的调试模式

我需要一种实时推送数组的方法,这是我唯一能想到的方法,另一种是使用Socket.io

我认为您可能是因为这个功能而将发布设置为 null:

this.storage.get('publications').then((val) => {
  this.publications = val;
});

您可以稍微更改它以确保发布仍然是一个数组

this.storage.get('publications').then((val) => {
   this.publications = val || [];
});

我添加了 this.publications = val || [];,如果 val 未定义,它会创建一个空数组