0

为了在 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);
                });
              }
        }

这是控制台输出: 在此处输入图像描述

更新播放列表后,您可以看到我想要传递到控制台的实际播放列表,但我没有在页面组件中收到它,

有任何想法吗?

谢谢

4

1 回答 1

1

哪个组件在调用setCurrentPlaylists()

最有可能的是,除 PagesComponent 之外的某个组件正在调用此方法,并且该其他组件可能已providers: [PagesService]在其元数据中进行了定义。这将导致PagesService创建两个实例——一个由 PagesComponent 提供(并注入),另一个由其他组件提供(并注入)。

于 2016-08-12T01:39:22.830 回答