将值从表单传递到服务,然后使用该值将数据提取到另一个组件?

时间:2018-05-22 08:35:06

标签: angular typescript

我目前正在将值从表单传递到服务。然后我根据该值从服务器获取数据,我想将该数据发送到与表单组件无关的另一个组件。

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>

表单组件Typescript

  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));
  }

1 个答案:

答案 0 :(得分:2)

试试这个。

<强>服务

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;
}

<强>组件

public ngOnInit(): void{
  this.movieService.getSingleMovieById().subscribe((value)=> console.log(value));
}

如果您在组件级别提供了服务。请将其删除并在唯一的模块中提供。

希望这有帮助。