Angular 2将数据从组件发送到服务 [英] Angular 2 send data from component to service

查看:79
本文介绍了Angular 2将数据从组件发送到服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是将数据从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.

基本上MyServiceComponent1接收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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆