简体   繁体   中英

Angular: how to share data from custom-component with app-component (app-root)

App-Component-Html: (which is in Index.Html as <app-root></app-root> )

<h2> {{currentOrNextWeek}} week from {{dateMonday}} to {{dateFriday}} </h2>
<div class="container"> <router-outlet></router-outlet> </div>

Custom-Component-TS: Is defined in routes -> router.module.ts and besides many other custom-components it has a table showing information realized by data from a service which sends get-requests to an API. Like this:

this.configService.getData.subscribe(data => organizeData(data))

The data itself has information like "Week = Current", "DateOfMonday=01.01.2021" (everything is a string)

How can I pass the data from custom.component to the app.component? I tried EventEmitter but I use <router-outlet> . As I understand correctly the sequence begins with app-component but the first GetData call is in custom-component, but the title is in the app-component-html

Your question seems to be how to exchange property between two component that are dynamic and does not need to be parent child. In that case communication through Service seems to be the best way to go.

You can create a service called AppCommunication with property tittle = new subject() that can have observable which is subscribed at app component and can be injected to you custom component so you can trigger the value from 'next'.

This can be used where ever you want to set it from.

you cant send this data using RXJS, behaviourSubject?

on some service:

varbSubject$ = new BehaviorSubject(<string>); 

on your app component:

bSubject$ = yourservice.varbSubject$
bSubject$.next("b");

on custom unknow element =>

bSubject$ = yourservice.varbSubject$
bSubject$.subscribe(value => {
  console.log("Subscription got", value); 
}); 

Have a look at @ThiagoNascimento post right underneath, it solved my problem!
Link: https://stackoverflow.com/a/70028739/17449921

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