为了在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);
});
}
}
更新播放列表后,您可以看到我要传递的实际播放列表打印到控制台,但我没有在页面组件中收到它,
有什么想法吗?
由于
答案 0 :(得分:1)
哪个组件正在调用setCurrentPlaylists()
?
最有可能的是,除PagesComponent之外的某些组件正在调用此方法,而其他组件可能在其元数据中定义了providers: [PagesService]
。这将导致创建两个PagesService
实例 - 一个是PagesComponent提供(和注入),另一个是其他组件提供(并注入)的实例。