ngOnInit
is executed when your component is initialized and your getCurrentMovie()
would for sure return undefined
because the value is not set yet. Later when you are setting the value your getCurrentMovie
method is not invoked either you force invoke it or go for Behavior Subject
I would suggest you go for RxJS BehaviorSubject
You can also use a regular RxJS Subject service, but here’s some advantages of it over subject
.
- It will always return the current value on subscription - there is no need to call
onnext().
- It has a getValue() function to extract the last value as raw data.
- It ensures that the component always receives the most recent data.
- you can get an observable from behavior subject using the
asobservable()
method on behavior subject.
- Refer this for more
your service
import { Injectable } from '@angular/core';
import {Imovie} from './imovie'
import {Observable,of,BehaviorSubject} from 'rxjs';
@Injectable()
export class ShareDataService {
private Movie= new BehaviorSubject<Imovie>(null);
currentMovie = this.Movie.asObservable();
constructor() { }
setCurrentMovie(movie:Imovie)
{
this.Movie.next(movie);
}
}
Component-1
import { Component, Input } from '@angular/core';
import {ShareDataService} from './share-data.service'
import {Imovie} from './imovie'
@Component({
selector: 'hello',
template: `<div *ngIf="currentMovie">
<h2>{{currentMovie.name}}</h2>
<h2>{{currentMovie.genre}}</h2>
</div>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
public currentMovie:Imovie;
constructor(public service:ShareDataService)
{
this.service.currentMovie.subscribe((value)=>{this.currentMovie=value
console.log(this.currentMovie);
});
}
}
Component-2
import { Component } from '@angular/core';
import {ShareDataService} from './share-data.service'
import {Imovie} from './imovie';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public movie:Imovie
constructor(public service:ShareDataService)
{
}
setMovie()
{
this.movie={name:'grudge',genre:'horror'};
this.service.setCurrentMovie(this.movie);
}
}
Component-2 HTML
<button (click)="setMovie()" >SetMovie</button>
<hello></hello>
LIVE DEMO