Hello I'm trying to send an object from 1. Component to 2. Component on a click event. Currently I try this using a data service who has a get- and set-function:
setDataObject(obj) {
this.subject.next(obj)
}
getDataObject(obj): Observable <any> {
return this.subject.asObservable()
}
On the 1. Component I trigger the setDataObject(obj) on a cliick event. On the 2. Component I'm now unsure how to subscribe correctly to the Observable and could just save the object from 1.Component to another variable. But I have read that you shouldn't use the observable that way. So how can I display the object and its properties in my HTML-Template? I already tried:
*ngIf = "observable$ | async as myObj"
but while my console.log shows the obj it doesn't get displayed in the template.
CodePudding user response:
This is a simple example of how you can set the observable within a basic service, then subscribe to it from another component.
After receiving the value from the observable, you can then display it within the calling component's HTML template using an async pipe observable.
Service
TS
@Injectable()
export class Service {
subject: Subject<number> = new Subject();
setDataObject(obj) {
this.subject.next(obj);
}
getDataObject(): Observable<any> {
return this.subject;
}
}
Client Component
TS
The code below we initialize the asynchronous observable without subscribing to it and provide a method to set the value of the observable within the service with a random number.
export class AppComponent {
displayObservable$: Observable<number>;
constructor(private api: Service) {
this.displayObservable$ = api.getDataObject().pipe(
map((res) => {
console.log('value from service = ' res);
return res;
})
);
}
sendValue(val: any) {
let num: number = Math.floor(Math.random() * 100);
console.log('value sent to service = ' num);
this.api.setDataObject(num);
}
}
HTML
The following HTML consists of a button to dispatch a value to the service and an
async
observable to display the response:
<div>Value from service = {{ displayObservable$ | async }}</div>
<p>
<button
type="button"
class="btn btn-primary"
id="btnSendValue"
(click)="sendValue($event)">
Send a value to service
</button>
</p>