Angular 2将数据从组件发送到服务

时间:2017-05-19 09:54:26

标签: javascript angular typescript angular-services angular-components

我的目标是将数据从Angular组件发送到服务并使用服务方法来处理它。例如:

    @Override
public void onBackPressed() {

FragmentManager fm = getActivity().getSupportFragmentManager();
    int count = fm.getBackStackEntryCount();

    if (count != 0) {
        fm.popBackStack ("fragment_name_tagB",FragmentManager.POP_BACK_STACK_INCLUSIVE);
    } else {
        super.onBackPressed();
    }
}

和服务:

export class SomeComponent {
    public data: Array<any> = MyData;
    public constructor(private myService: MyService) {
      this.myService.data = this.data;
    }
}

获取数据未定义。如何使其有效?

2 个答案:

答案 0 :(得分:10)

如果服务和组件之间的交互可能是:

的示例

<强>服务

@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);
    }
}

组件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!
            }
        );
    }
}

<强>解释

MyService正在管理data。如果您愿意,您仍然可以使用data执行操作,但最好将其留给Component2

基本上MyServicedata收到Component1,并将其发送给订阅方法myMethod()的任何人。

Component1正在dataMyService发送Component2myMethod()已订阅myMethod(),因此每次Component2被调用时,myMethod()都会收听{{1}}正在返回的内容。

答案 1 :(得分:0)

@SrAxi的回复中的接收器组件存在一个小问题,因为它无法订阅服务数据。考虑使用BehaviorSubject而不是Subject。它对我有用!

private myMethodSubject = new BehaviorSubject<any>("");