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);
}
}
组件 1(发送方):
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屋!