我有这个结构
app/
--pages/
----pages.component.ts
--channel/
----shared/
------assignPlaylist.modal.ts
在 pages.component.ts 中,我有一个名为 playlist 的变量
export class PagesComponent {
@Input() platform: Platform;
@Output() onPlaylistsChange: EventEmitter<Playlists>;
currentPageName: string;
currentPage: Page;
pages: Array<Page>;
playlists: Playlists;
}
在 assignPlaylist.modal.ts 中,我创建了一个 http post 方法,它返回一个新的播放列表,我需要使用返回的播放列表来替换 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);
}
);
}
}
);
这是播放列表的构造函数
export class Playlists {
headerPlaylists: Array<Playlist>;
bodyPlaylists: Array<Playlist>;
wholePlaylists: Array<Playlist>;
}
-----更新--------------------- 正如答案中提到的,我做了以下更改.
@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);
}
}
控制台显示“我在这里”,
我写在我的 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);
});
}
但是,我没有看到“新播放列表来了”的消息,是我用错了吗?
新更新:我检查了this.playlists,它的观察者是0,为什么?