Lets say i have observable
public myObservable$: Observable<SomeModel> | undefined;
and non observable
public myNonObservable: SomeModel | undefined;
And i am filling it like this
ngOnInit() {
this.myObservable$ = ....
}
How can i get data from myObservable$
and copy it to myNonObservable
? Because thing like map and object assign seems to not work here.
You need to subscribe
to an observable. The observable is a stream, that means SomeModel | undefined
that can change its value by time. When you subscribe to the observable, you read that stream by providing a callback function that is executed, every time a new value arrives in the stream.
this.myObservable$.subscribe((model: SomeModel | undefined) => ...)
If you subscribe to an observable, you also need to unsubscribe, when you don't need to listen to the observable anymore, e.g. when the component gets destroyed. You can either store the subscription in another member variable, or you use a better way of subscribing to an observable. Angular provides a async
pipe. This pipe handles the whole subscription/unsubscribe process for you. In your template you can do the following
<my-other-component [model]="myObservable$ | async">
</my-other-component>
And in the OtherComponent
you can define an @Input
that is directly the model.
@Component(...)
export class OtherComponent {
@Input() model: SomeModel|undefined;
}