代码之家  ›  专栏  ›  技术社区  ›  sander

将值从窗体传递到服务,然后使用该值将数据提取到其他组件?

  •  0
  • sander  · 技术社区  · 7 年前

    我当前正在将值从窗体传递到服务。然后,我将基于该值从服务器获取数据,我希望将该数据发送到另一个与表单组件无关的组件。

    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));
      }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Anuradha Gunasekara    7 年前

    试试这个。

    服务

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

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

    希望这有帮助。

    推荐文章