Angular 2将数据从组件发送到服务 [英] Angular 2 send data from component to service
问题描述
我的目标是将数据从Angular组件发送到服务,并使用服务方法对其进行处理.示例:
My target is to send data from Angular component to service and use service methods to work on it. Example:
export class SomeComponent {
public data: Array<any> = MyData;
public constructor(private myService: MyService) {
this.myService.data = this.data;
}
}
和服务:
@Injectable()
export class TablePageService {
public data: Array<any>;
constructor() {
console.log(this.data);
// undefined
}
}
获取数据是不确定的.如何使它起作用?
Getting data is undefined. How to make it works?
推荐答案
服务和组件之间的交互可能是一个示例:
An example if interaction between service and component could be:
服务:
@Injectable()
export class MyService {
myMethod$: Observable<any>;
private myMethodSubject = new Subject<any>();
constructor() {
this.myMethod$ = this.myMethodSubject.asObservable();
}
myMethod(data) {
console.log(data); // I have data! Let's return it so subscribers can use it!
// we can do stuff with data if we want
this.myMethodSubject.next(data);
}
}
Component1(发送方):
export class SomeComponent {
public data: Array<any> = MyData;
public constructor(private myService: MyService) {
this.myService.myMethod(this.data);
}
}
Component2(接收方):
export class SomeComponent2 {
public data: Array<any> = MyData;
public constructor(private myService: MyService) {
this.myService.myMethod$.subscribe((data) => {
this.data = data; // And he have data here too!
}
);
}
}
说明:
MyService
正在管理data
.您仍然可以根据需要使用data
进行操作,但是最好将其留给Component2
.
MyService
is managing the data
. You can still do stuff with data
if you want, but is better to leave that to Component2
.
基本上MyService
从Component1
接收data
并将其发送给预订了方法myMethod()
的任何人.
Basically MyService
receives data
from Component1
and sends it to whoever is subscribed to the method myMethod()
.
Component1
正在将data
发送到MyService
,这就是他所做的全部.
Component2
订阅了myMethod()
,因此每次调用myMethod()
时,Component2
都会监听并获取myMethod()
返回的内容.
Component1
is sending data
to the MyService
and that's all he does.
Component2
is subscribed to the myMethod()
so each time myMethod()
get called, Component2
will listen and get whatever myMethod()
is returning.
这篇关于Angular 2将数据从组件发送到服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!