Issue
I'm currently passing a value from form to a service. Then I'm fetching data from server based on that value and I would like to send that data to another component which is not related to the form component.
Form -> Service -> Server
Server-> Service -> Component
Service
_currentMovie: Observable<IMovie>; // This is where the fetched data gets saved
getSingleMovieById(movieId: number){
let urlWithId: string = this._singleMovieUrl.concat(movieId.toString());
this._currentMovie = this._http.get<IMovie>(urlWithId);
}
Component
ngOnInit(){
this._movieService._currentMovie.subscribe((value)=> console.log(value));
}
I get the correct data from server to the service, but can't use it in the component. This gives an error:
ERROR TypeError: Cannot read property 'subscribe' of undefined
Error Log:
ERROR TypeError: Cannot read property 'toString' of undefined
at MovieService.getSingleMovieById2 (movie.service.ts:80)
at MovieDetailsComponent.getCurrentMovie2 (movie-details.component.ts:81)
at MovieDetailsComponent.ngOnInit (movie-details.component.ts:63)
at checkAndUpdateDirectiveInline (core.js:12411)
at checkAndUpdateNodeInline (core.js:13935)
at checkAndUpdateNode (core.js:13878)
at debugCheckAndUpdateNode (core.js:14771)
at debugCheckDirectivesFn (core.js:14712)
at Object.eval [as updateDirectives] (MovieDetailsComponent_Host.ngfactory.js? [sm]:1)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14697)
Form Component HTML
<a [routerLink]="['/details']" href="/details" (click)="setCurrentMovie2(movie)">Details</a>
Form component Typescript
setCurrentMovie2(movie: IMovie){
this._movieService.setCurrentMovie2(movie.MovieID);
}
Service
setCurrentMovie2(Id: number){
this.movieID = Id;
console.log("movieid", this.movieID);
}
getSingleMovieById2(): Observable<IMovie>{
let urlWithId: string = this._singleMovieUrl.concat(this.movieID.toString()); // This is where error happens
return this._http.get<IMovie>(urlWithId);
}
Details Component
getCurrentMovie2(){
this._movieService.getSingleMovieById2().subscribe((value)=>console.log(value));
}
Solution
Try this:
Service
public id: number;
public getSingleMovieById(): Observable<IMovie> {
const url = `${this.baseUrl}/${this.id}`;
return this.http.get<IMovie>(url);
}
// call this method from the first component which you have a form in it.
public setId(id: number): void {
this.id = id;
}
Component
public ngOnInit(): void{
this.movieService.getSingleMovieById().subscribe((value)=> console.log(value));
}
And if you have provided your service in the component level. Please remove that and provide it in a only module.
Answered By - Anuradha Gunasekara
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.