2017-09-09 21 views
0

我试图使用主题和共享服务将数据从一个组件传输到另一个组件。但它不起作用。无法在使用RxJS主题/共享服务的组件之间传递数据

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

我的服务(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)); 
    }   
} 

回答

2

我认为这是因为您在订阅的SubjectListComponent后您发出使用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是正是一篇很棒的帖子。

+0

美丽!现在完美运作。也感谢那篇文章。那么你什么时候会选择Subject over BehaviorSubject?似乎后者是在传递组件数据时要走的路。 – ZeroDarkThirty

+0

太棒了,很高兴我能帮到你!如果您只对从订阅点开始的源发出的值感兴趣,请使用主题。如果您还需要订阅之前发布的最后一个值(如您的情况),请使用BehaviourourSubject。 – David

相关问题