Javascript Angular 2 将数据从组件发送到服务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44066905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 send data from component to service
提问by IntoTheDeep
My target is to send data from Angular component to service and use service methods to work on it. Example:
我的目标是将数据从 Angular 组件发送到服务并使用服务方法来处理它。例子:
export class SomeComponent {
public data: Array<any> = MyData;
public constructor(private myService: MyService) {
this.myService.data = this.data;
}
}
and service:
和服务:
@Injectable()
export class TablePageService {
public data: Array<any>;
constructor() {
console.log(this.data);
// undefined
}
}
Getting data is undefined. How to make it works?
获取数据未定义。如何使它起作用?
回答by SrAxi
An example if interaction between service and component could be:
如果服务和组件之间的交互可以是一个示例:
Service:
服务:
@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 (sender):
组件 1(发送方):
export class SomeComponent {
public data: Array<any> = MyData;
public constructor(private myService: MyService) {
this.myService.myMethod(this.data);
}
}
Component2 (receiver):
组件 2(接收器):
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!
}
);
}
}
Explanation:
解释:
MyServiceis managing the data. You can still do stuff with dataif you want, but is better to leave that to Component2.
MyService正在管理data. data如果你愿意,你仍然可以做一些事情,但最好把它留给Component2.
Basically MyServicereceives datafrom Component1and sends it to whoever is subscribed to the method myMethod().
基本上从订阅该方法的任何人MyService接收并将其发送给任何人。dataComponent1myMethod()
Component1is sending datato the MyServiceand that's all he does.
Component2is subscribed to the myMethod()so each time myMethod()get called, Component2will listen and get whatever myMethod()is returning.
Component1正在发送data给MyService,这就是他所做的一切。
Component2订阅了myMethod()所以每次myMethod()被调用时,Component2都会收听并获取myMethod()返回的内容。
回答by Debo
There is a small issue with the receiver component in @SrAxi s reply as it can't subscribe to the service data. Consider using BehaviorSubject instead of Subject. It worked for me!
@SrAxi 的回复中的接收器组件存在一个小问题,因为它无法订阅服务数据。考虑使用 BehaviorSubject 而不是 Subject。它对我有用!
private myMethodSubject = new BehaviorSubject<any>("");

