我正在使用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);
}
});
现在我的问题是:当我试图将数据推送到数组中时,它告诉我它不能读取null的属性(this.publications)。
当进入事件的订阅时,它不接受组件中定义的变量。有什么办法吗?
EDIT:
我的组件HomePage
@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++;
}
调试模式
我需要一个实时推送数组的方法,这是我能想到的唯一方法,另一个方法是使用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
未定义