Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

How can I share an array of objects between two components using observables in angular?

I am new to observables. Can anybody tell me how to set and get an array of objects and share it between two component using observables in Angular.

Thanks

question from:https://stackoverflow.com/questions/65643467/how-can-i-share-an-array-of-objects-between-two-components-using-observables-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since you're asking about observables I assume your two components are not parent and child thus Inputs & Outputs aren't what you're looking for.

To share data between components like that you need a service you can simply generate one with
ng generate service nameOfYourService

You can then add that service the components' contructors and the Dependency Injection will provide the same instance of the service to both (this is the default behaviour).

So basically in this way the can already share data, if you put an array in that service both can simply read that array as a field of the service, so you don't need observables for that.

You can store the array in a Subject or BehaviousSubject which basically wraps your array in an observable and you can update its value by calling its method next(newValue) and you can listen to the value by subscribing (subscribe) to the Subject.

This is a very very simplistic and basic explanation, there are many alternatives and you can use depending on what you want/need to achieve (which from your question is not really clear).


I'd strongly suggest you to look better into services and observables, the tour of hero's section on services should help you greatly (and it does show how to share an array wrapped in an observable): https://angular.io/tutorial/toh-pt4


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...