当我单击按钮时,我试图显示一个组件。该组件和按钮位于两个不相关的类中,因此我正在使用“行为主题”模块。但是,按钮和服务之间的链接不会将布尔值更改为“ true”,并且我无法弄清楚原因。这是我的代码:
Data.service.ts:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';
@Injectable()
export class DataService{
private showEventForm = new BehaviorSubject<boolean>(false);
currentShowEventForm = this.showEventForm.asObservable();
constructor(){ }
editShowEventForm(newClick){
this.showEventForm.next(newClick);
}
}
HTML:
<button type="button" class="btn btn-primary" (click)="toggleEventForm()">
Post Event</button>
Ts:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'vhub-postEvent',
templateUrl: './postevent.component.html',
styleUrls: ["./postevent.component.css"]
})
export class PostEventComponent implements OnInit{
showEventForm: boolean = false;
constructor(private mydata: DataService) {
}
ngOnInit() {
this.mydata.currentShowEventForm.subscribe(showEventForm => this.showEventForm = showEventForm);
}
toggleEventForm(): void{
this.showEventForm = !this.showEventForm;
}
}
答案 0 :(得分:1)
您需要向服务发送showEventForm
数据才能更改BehaviorSubject
的值。
toggleEventForm(): void{
this.showEventForm = !this.showEventForm;
this.mydata.editShowEventForm(this.showEventForm);
}