Angular 5 - 提交时将数据从一个组件传递到另一个组件

Angular 5 - passing data from one component to another when submit

在 Angular5 中,我想将一个值从一个组件传递到另一个组件(同级)。为此,我创建了一个公共服务,如下所示:

import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class DataService {

    private data = {};

    constructor() { }

    setOption(option, value) {
        this.data[option] = value;
    }

    getOption() {
        return this.data;
    }
}

在组件#1 中,我写了以下内容:

onSubmit(form: NgForm){
  this._dataService.setOption('image', form.value.image);
}

在组件#2 中,我想获取值并像这样控制它:

ngOnInit() {
 this.sharedData = this._dataService.getOption();
 console.log(this.sharedData.image);
}

但是,它在控制台中显示 undefined

您可以改用 observable :

export class DataService {

    private data = new BehaviorSubject<any>({});
    // behavior subject will keep in mind the last value so if the parent
    // emit before the first component is mounted, it will not receive the value
    // subject would not that is the difference


   // private data = new Subject<any>(); <-- Arnaud Denoyelle's solution

    constructor() { }

    setOption(option, value) {
        const options = this.data.getValue();
        options[option] = value;
        this.data.next(options);
        // .next will emit a new value to every subscription
    }

    get option() {
        return this.data.asObservable();
    }
}

像这样使用它:

ngOnInit() {
 this.sub = this._dataService.option.subscribe(data => {
     this.sharedData = data; // each time option will change, sharedData will too
     console.log(this.sharedData);
 });
}

ngOnDestroy() {
   this.sub.unsubscribe(); // clear to avoid memory leak
}

组件 1 不会更改:

onSubmit(form: NgForm){
  this._dataService.setOption('image', form.value.image);
}

尝试将 data 更改为 BehaviorSubjectSubject(如果您不需要初始数据),例如:

private data = new BehaviorSubject<any>({});

然后更改您的 setOptiongetOption 方法来使用它:

setOption(value){
    this.data.next(value);
}

getOption(): Observable<any>{
   return this.data.asObservable();
}

然后在组件#2 中订阅由 getOption 返回的 Observable :

this._dataService.getOption()
.subscribe((data)=>{
    this.sharedData = data;
});

请记住通过 takeUntil rxjs 或其他一些方法取消订阅 Observable 以避免内存泄漏。