我当前正在将值从窗体传递到服务。然后,我将基于该值从服务器获取数据,我希望将该数据发送到另一个与表单组件无关的组件。
Form -> Service -> Server
Server-> Service -> Component
服务
_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);
}
组件
ngOnInit(){
this._movieService._currentMovie.subscribe((value)=> console.log(value));
}
我从服务器获取正确的数据到服务,但不能在组件中使用它。这会产生一个错误:
ERROR TypeError: Cannot read property 'subscribe' of undefined
错误日志:
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)
表单组件HTML
<a [routerLink]="['/details']" href="/details" (click)="setCurrentMovie2(movie)">Details</a>
表单组件类型脚本
setCurrentMovie2(movie: IMovie){
this._movieService.setCurrentMovie2(movie.MovieID);
}
服务
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);
}
详细信息组件
getCurrentMovie2(){
this._movieService.getSingleMovieById2().subscribe((value)=>console.log(value));
}