0

我想将一个对象传递给另一个组件。下面是我的方法。但是数据在路线改变时被清除。是否有任何解决方案或是否有任何其他解决方案。

在组件 1 中:

this.myService.setData(this.myData);
this.router.navigateByUrl('component2');

在职:

private myDataSubj = new Subject<MyData>();
setData(myData) {
    this.myDataSubj.next(myData);
}
getData(): Observable<MyData> {
    return this.myDataSubj.asObservable();
}

在组件 2 中: 在 ngOninit

this.myService.getData().subscribe(data => {
     this.myData = data;
     console.log(this.myData); // Returning Undefined. 
  })

我错过了什么吗?

4

1 回答 1

0

请在询问之前阅读角度文档或做一些研究。请阅读有关使用服务的 Angular 组件交互

在高层次上,你想要的是...... [见下文]

更新

支持 Angular 5

模块

providers: [SharedService]
exports: [SharedService]

服务

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs';
import { SharedService } from '........<module path>...';

@Injectable()
export class SharedService {

  // Observable string sources
  private myDataSubj = new Subject<MyData>();

  // Observable string streams
  public myDataSubj$ = this.myDataSubj.asObservable();

  // Service method
  sharedData(myData: MyData) {
    this.myDataSubj.next(myData);
    this.myDataSubj.complete();
  }

}

组件一

this.sharedService.sharedData(data);

组件-2

this.sharedService.myDataSubj$.subscribe(data => {
    this.myData= data;
    console.log(this.myData);
});
于 2020-03-17T06:24:45.587 回答