无法使用RxJS主题/共享服务在组件之间传递数据

时间:2017-09-09 11:51:19

标签: angular rxjs

我正在尝试使用Subject和共享服务将数据从一个组件传输到另一个组件。但它没有用。

请注意,我在模块级别而不是组件装饰器中列出了服务。也许值得注意的是,这两个组件不共享父子关系。

我的服务(SearchService):

import { Subject } from 'rxjs/Subject';

@Injectable()
export class SearchService {
  public messageSource = new Subject<any>();

  constructor() { }

  topAlbums(album){
    this.messageSource.next(album);
  }

}

组件1(即发送数据)。当触发createList()时,它会完美地导航到新路由,但我在下面订阅的消息(在组件2中)不会显示。

    import { SearchService } from '../../services/search.service';

    export class AlbumComponent implements OnInit {
    private UNIQUE_ID: string;
    constructor(private _service: SearchService, private _http: Http, private router: Router) { }

    //Linked to a click event handler
    createList(){
        //API Call to retrieve an ID
        this._http.post('https://api.url', data)
            .map(res => res.json())
            .subscribe(item => {
              this.ID = item.id;
              let parsed_JSON = JSON.parse(item.files.myAlbums.content);
              this.router.navigate(['/list', this.UNIQUE_ID]);
            })
       this._service.topAlbums("Testing out by sending a dummy message");

 }

组件2(接收数据):

import { SearchService } from '../../services/search.service';

    export class ListComponent implements OnInit {
    constructor(private _service: SearchService) { }
    ngOnInit(){
      this._service.messageSource.subscribe(data => console.log(data));
    }          
 }

1 个答案:

答案 0 :(得分:2)

我认为这是因为您使用Subject在之后订阅了ListComponent 中的next()。请改用BehaviorSubject。订阅BehaviorSubject时,它会发出最后一个值。因此,它还需要具有初始值:

let bSubject = new BehaviorSubject(null);

bSubject.next(album);

bSubject
 .filter(value => value !== null) // filter out the initial null value to avoid problems if you did not emit anything before subscribing
 .subscribe((value) => {
  console.log(value); // logs your album
 }

Here就这个主题发表了一篇很棒的文章。