How to transfer data from the component to the service?
1 answer
An example of the interaction between a service and a component:
Service:
@Injectable() export class MyService { myMethod$: Observable<any>; private myMethodSubject = new Subject<any>(); constructor() { this.myMethod$ = this.myMethodSubject.asObservable(); } myMethod(data) { console.log(data); // У нас есть данные! Давайте вернем их, чтобы подписчики могли его использовать! // тут мы можем делать что-нибудь с данными this.myMethodSubject.next(data); } } Component1 (sender):
export class SomeComponent { public data: Array<any> = MyData; public constructor(private myService: MyService) { this.myService.myMethod(this.data); } } Component2 (Recipient):
export class SomeComponent2 { public data: Array<any> = MyData; public constructor(private myService: MyService) { this.myService.myMethod$.subscribe((data) => { this.data = data; // И тут тоже мы можем пользоваться нашими данными! } ); } } Explanation:
My Service manages data . You can still work data if you want, but it’s better to leave it for Component2 . Basically, MyService gets data from Component1 and sends it to the person who subscribed to the myMethod () method.
Component1 sends data to MyService , and that’s all it does. Component2 subscribes to myMethod () , so every time myMethod () is called, Component2 will listen and receive everything that myMethod () returns.
The answer is taken and translated from the question Angular 2
|