how to pass data between unrelated components angular 10

Viewed 1726

i want to pass the id of a select value to another unrelated component

component 1 :

Html

<select (change)="getSelectedStoreId($event.target.value)">
   <option *ngFor="let store of stores.slice().reverse()" value="{{store.id}}">
      {{store.name}} 
   </option>
</select>

Ts

storeId: any;
getSelectedStoreId(store: any) {
 this.storeId = store;
}

Component 2:

loadItemByStore(storeId: number) {
   this.service.getItemByStore(storeId).subscribe((res: 
   HttpResponse<Item[]>) => {
   this.data= res.body || [];
  }); 
 }
2 Answers

Use a shared service with Subject or BehaviorSubject, like this:

// service.ts

@Injectable({
 providedIn: 'root'
})
export class MyService {
 sharedValue$ = new Subject();
}

// component a

@Component({
 ...
})
export class ComponentA implements OnInit {
constructor(private myService: MyService) {
}

ngOnInit() {
 // get data
 this.myService.sharedValue$.subscribe(data => {
  // data will update here upon changes
  console.log(data) // 100
 })
}


}

// component b

@Component({
 ...
})
export class ComponentB implements OnInit {
constructor(private myService: MyService) {
}

ngOnInit() {
 // set data
 this.myService.sharedValue$.next(100)
}


}

One good solution is to create an external service that contains this information. The service has a function to get and set/update the value. Then, each time you modify the value in one component, you update it using the service. In the other component you can read this value. You can see an example in this question: this question.

If it is not clear, I can create a specific example.

Related