为了在 angular2 不同组件之间传递值,我使用注入不同组件的不同服务。
在我的 PagesService 组件中,我定义了一个行为主题并希望传递一个值。
import { Injectable } from '@angular/core';
import { ApiService } from '../../apiService/api.service';
import { Playlists } from '../shared/playlists.model';
import { Subject, BehaviorSubject } from 'rxjs/Rx';
@Injectable()
export class PagesService {
private currentPlaylists: Subject<Playlists> = new BehaviorSubject<Playlists>(new Playlists());
constructor(private service: ApiService) {
}
getCurrentPlaylists() {
return this.currentPlaylists.asObservable();
}
setCurrentPlaylists(playlists: Playlists) {
console.log(playlists, 'i am here');
this.currentPlaylists.next(playlists);
}
}
我需要将播放列表传递给一个名为 PagesComponent 的组件
import { Component, OnInit, Input, Output, OnChanges, EventEmitter, Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { PagesService } from './shared/pages.service';
import { Subject,BehaviorSubject } from 'rxjs/Rx';
@Component({
selector: 'pages',
styleUrls: ['app/pages/pages.css'],
templateUrl: 'app/pages/pages.html',
providers: [PagesService]
})
export class PagesComponent {
playlists: Playlists;
constructor(private service: PagesService, private playlistService: PlaylistService) {
this.playlists = new Playlists();
this.service.getCurrentPlaylists().subscribe((playlists) => {
console.log(playlists, 'new playlists coming');
this.playlists = playlists;
}, error => {
console.log(error);
});
}
}
更新播放列表后,您可以看到我想要传递到控制台的实际播放列表,但我没有在页面组件中收到它,
有任何想法吗?
谢谢