当页面也在变化时,我需要在两个组件之间传递数据。为此,我实现了一个数据服务:
@Injectable()
export class DatashareService {
public dataSubject = new Subject<any>();
public addData(data){
this.dataSubject.next(data);
}
}
并使用 addData 方法将数据传递给它:
export class DashboardDialog {
dashboardName;
dashboardDescription;
.....
addElements() {
this.dataShare.addData({dashboardName: "a name", dashboardDescription:"a description"});
this.router.navigate(["dashboards/new"]);
this.closeDialog();
}
}
我在我的其他组件中订阅了它的数据:
export class NewDashboardDesign implements OnInit {
dashboardName;
xmlContent;
constructor(private dataShare: DatashareService) {
}
ngOnInit() {
this.dataShare.dataSubject.subscribe(
data => {
this.dashboardName = data.dashboardName;
this.xmlContent = "<dashboard>\n" +
sprintf("<name> '%s' </name>\n", this.dashboardName) +
"</dashboard>\n";
}
);
}
但是,我的 html 元素没有更新为新内容(尽管我得到了数据):
<mat-form-field>
<textarea matInput placeholder="XML" [(ngModel)]='xmlContent' #xml></textarea>
</mat-form-field>