问题
In order to pass value between angular2 different components, I use different services injected into different components.
In my PagesService component, I define a behavior subject and want to pass a value.
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);
}
}
I need to pass the playlists to a component called 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);
});
}
}
This is the console output:
After I update the playlists, you can see the actual playlists I want to pass printed out to the console, but I do not receive it in pages component,
Any ideas?
Thanks
回答1:
Which component is calling setCurrentPlaylists()
?
Most likely, some component other than PagesComponent is calling this method and that other component probably has providers: [PagesService]
defined in its metadata. This will result in two instances of PagesService
being created – one that PagesComponent provides (and injects), and another instance that some other component provides (and injects).
来源:https://stackoverflow.com/questions/38906315/observable-do-not-receive-the-next-value-in-angular2