简体   繁体   中英

Angular 2+: data binding using Subjects is not working in ngOnInit

I need to communicate data between two component while the page is also changing. To do this, I implemented a data service:

@Injectable()
export class DatashareService {
    public dataSubject = new Subject<any>();
    public addData(data){
        this.dataSubject.next(data);
    }
}

and pass data to it using addData method:

export class DashboardDialog {
    dashboardName;
    dashboardDescription;
    .....
    addElements() {
            this.dataShare.addData({dashboardName: "a name", dashboardDescription:"a description"});
            this.router.navigate(["dashboards/new"]);
            this.closeDialog();
        }
    }

I subscribed to its data in my other component:

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";
            }
        );
    }

However, my html element does not get updated with the new content (although I get the data):

<mat-form-field>
   <textarea matInput placeholder="XML" [(ngModel)]='xmlContent' #xml></textarea>
</mat-form-field>

I assume from your description that the two Components between which you are attempting to communicate are both 'top-level' components (you are routing from one to the other).

This means that the two of them are never in existence at the same time. So, the first component is 'publishing' via the DatashareService, but the second component is not there to receive the data. The subscription happens after the event is emitted.

To fix this, change your Subject to a BehaviorSubject. Unlike Subject, BehaviorSubject emits the last event upon subscription.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM