Using observable talk to other component in angular2, not receiving coming value

非 Y 不嫁゛ 提交于 2019-12-13 05:25:58

问题


I have this structor

app/
  --pages/
  ----pages.component.ts 
  --channel/
  ----shared/
  ------assignPlaylist.modal.ts

Inside the pages.component.ts, I have a variable called playlist

export class PagesComponent {

  @Input() platform: Platform;

  @Output() onPlaylistsChange: EventEmitter<Playlists>;

  currentPageName: string;

  currentPage: Page;

  pages: Array<Page>;

  playlists: Playlists;
}

In assignPlaylist.modal.ts, I make an http post method and it returns a new playlists, I need to use that returned playlists to replace the playlists in pages.component.ts

this.apiService.addPlaylistToPage(playlistId, stDate, etDate, this.apiService.getGlobalRegion(), callback)
          .subscribe(
            data => {
              if (this.apiService.g_platform == 'DESKTOP') {
                this.apiService.getPlaylist(this.apiService.getCurrentPage(), 'true' )
                .subscribe(
                  res => {                          this.pagesService.setCurrentPlaylists(res.playlists);
                  }
                );
            } else {
              this.apiService.getPlaylist(this.apiService.getCurrentPage(), 'false' )
              .subscribe(
                res => {           this.pagesService.setCurrentPlaylists(res.playlists);
                }
              );
            }
            }
          );

This is the res, return results

And this is the structor of playlists

export class Playlists {
  headerPlaylists: Array<Playlist>;
  bodyPlaylists: Array<Playlist>;
  wholePlaylists: Array<Playlist>;
}

----------------Update---------------------- As mentioned in the answer, I did the following changes.

@Injectable()
export class PagesService {

  private currentPlaylists: Subject<Playlists> = new BehaviorSubject<Playlists>(new Playlists());
  getCurrentPlaylists() {
    return this.currentPlaylists.asObservable();
  }

  setCurrentPlaylists(playlists: Playlists) {
    console.log('i am here');
    this.currentPlaylists.next(playlists);
  }
}

And the console shows 'I am here',

I write in my pages.component.ts

 constructor(private service: PagesService, private playlistService: PlaylistService) {
    this.pages = [];
    this.currentPage = new Page();
    this.service.setCurrentPage(this.currentPage);
    this.playlists = new Playlists();
    this.onPlaylistsChange = new EventEmitter<Playlists>();
    this.service.getCurrentPlaylists().subscribe((playlists) => {
      console.log(playlists, 'new playlists coming');
      this.playlists = playlists;
    }, error => {
      console.log(error);
    });
  }

However, I did not see the message ' new playlists coming', am I using it wrong?

New update: I checked the this.playlists, it's observers is 0, why?


回答1:


Do create a PlaylistService that exposes an observable that PagesComponent can subscribe to.

import { Injectable} from '@angular/core';
import { Subject,BehaviorSubject } from 'rxjs';
import {Playlists} from 'channel' /** Assumes this is where you have defined your Playlists interface **/

@Injectable()
export class PlaylistService {
    private _currentPlaylists$: Subject<Playlists> = new BehaviorSubject<Playlists>(null);
    constructor() {}

    currentPlaylists() {
      return this._currentPlaylists$.asObservable();
    }

    setCurrentPlaylists(playlists:Playlists){
      this._currentPlaylists$.next(playlists);
    }
}

Then import this service into your pagescomponent and subscribe to playlists as shown below:-

this.playlistService.currentPlaylists().subscribe((playlists) => {
      this.playlists = playlists;
},error => {
    console.log(error);
});`

Please do bear in mind you will also have to import this service into your assignPlaylistModal and use it like this:-

   this.apiService.addPlaylistToPage(playlistId, stDate, etDate, this.apiService.getGlobalRegion(), callback)
      .subscribe(
        data => {
          if (this.apiService.g_platform == 'DESKTOP') {
            this.apiService.getPlaylist(this.apiService.getCurrentPage(), 'true' )
            .subscribe(
              res => {
                this.playListService.setCurrentPlaylists(res);
              }
            );
        } else {
          this.apiService.getPlaylist(this.apiService.getCurrentPage(), 'false' )
          .subscribe(
            res => {
              this.playListService.setCurrentPlaylists(res);
            }
          );
        }
        }
      ); 

Do read more about observables to understand why am using BehaviourSubject here. http://reactivex.io/documentation/observable.html



来源:https://stackoverflow.com/questions/38881264/using-observable-talk-to-other-component-in-angular2-not-receiving-coming-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!