简体   繁体   中英

how to send value to another unrelated component in angular 11?

in home component, a line like...<app-root [message]="hii"> is opening that app-root comp, with value to app-root component which has @input and {{message}} in html is working..

But i need to redirect to that app-root component instead of opening in current component.

any ways like "button onclick to redirect to that with [message]="hi" as data?

the best way to shared data between an unrelated component in the angular is, use the "BehaviorSubject" from rxjs library.

we imagine that we have two components that there are completely unrelated and we want to shared data between them. first of all, you should create a service file. Imagine that we have a service with the name of sharing-data.serice.ts:

 import { BehaviorSubject, Subject } from 'rxjs'; import { Injectable } from '@angular/core'; @Injectable({ providedIn:'root' }) export class SharingDataService { public subject = new BehaviorSubject(""); getDataFromFirstComponent(x){ this.subject.next(x); } sharedDataWithSecondComponent(){ return this.subject.asObservable(); } }
here we use BehaviorSubject class to make a pipe between unrelated components for transferring data.

in the first component.ts we inject the service by dependency injection, then make a method to use this service and fill the pipe by data:

 constructor( private service: SharingDataService, ) { } sendDataOutOftheComponent(){ this.service.getDataFromFirstComponent(this.dataFormFirst); }

now in the second component we just need to use this service again and after that subscribe to the method to get the data. in the second component.ts we have the following code:

 constructor( private service: SharingDataService, ) { } getDataFromFirstComponent(){ this.service.sharedDataWithSecondComponent().subscribe(data=>{ this.dataFromFirst= data; }) }

with this method, you can easily shared data between unrelated components in the angular

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