NG子组件不调用服务

时间:2019-04-07 15:26:07

标签: angular angular-services

我有2个组件:NowRunningComponent和MovieDetailComponent。在NowRunningComponent中的单击事件上,我正在MovieDetailComponent中设置Input()selectedMovie。在MovieDetailComponent中,我正在听ngOnChanges,并在属性更改时调用YT服务。我已经在MovieDetailComponent中注入了YouTube服务。但是,HTML中的NowRunningComponent面临错误。

NowRunningComponent.html:8 ERROR TypeError: this.ytService.getYTvideos is not a function
    at MovieDetailComponent.push../src/app/movie-detail/movie-detail.component.ts.MovieDetailComponent.ngOnChanges (movie-detail.component.ts:26)
    at checkAndUpdateDirectiveInline (core.js:20661)
    at checkAndUpdateNodeInline (core.js:21929)
    at checkAndUpdateNode (core.js:21891)
    at debugCheckAndUpdateNode (core.js:22525)
    at debugCheckDirectivesFn (core.js:22485)

NowRunningComponent.ts:

@Component({
  selector: 'app-now-running',
  templateUrl: './now-running.component.html',
  styleUrls: ['./now-running.component.css']
})
export class NowRunningComponent implements OnInit {

  constructor(private nowrunningService: NowRunningServiceService) { }
  movies: Array<Movie>=[];
selectedMovie: Movie;
  ngOnInit() {
    console.log("MOvies length"+ this.movies);
    this.nowrunningService.getNowRunningMovies().subscribe((data:any) => {
      this.movies= data.results;

    });

  }

  posterClick(movie: Movie) {
    this.selectedMovie=movie;
    console.log(this.selectedMovie.original_title + " Selected.")
    console.log(this.selectedMovie.title + " Selected.")
  }
}

NowRunning组件HTML:

...
<app-movie-detail [selectedMovie] = "selectedMovie"></app-movie-detail>
...

MovieDetailComponent.ts

export class MovieDetailComponent implements OnInit,OnChanges {

  @Input()
  selectedMovie:Movie;
  constructor(private ytService: YoutubeService) { }

  ngOnInit() {
    console.log('movie detail init');
  }
  videos:Array<any>=[];
  ngOnChanges(changes: SimpleChanges) {

    console.log('movie changed');
    console.log(`Changes: ${JSON.stringify(changes)})`);
     if(this.selectedMovie.title!= null)
      {
        this.ytService.getYTvideos(this.selectedMovie.title).subscribe((data:any) => {
          this.videos= data.items;

        });
      }
  }

}

YouTubeService.ts

@Injectable({
  providedIn: 'root'
})
export class YoutubeService {

  search_url = "/yt-vid/";
  constructor(private http:HttpClient) { }

  getYTvideos (title) {
    return this.http.get(globals.api_base_href+this.search_url+title);
  }
}

该错误是从NowRuningComponent HTML生成的。您能在这里分享您的想法吗?我应该做EventEmitter吗?

1 个答案:

答案 0 :(得分:0)

首先,

  getYTvideos (title) {

getYTvideos(title)之间的空格看起来像语法错误。至少当我尝试以这种方式声明一个函数时,它就像一个人。

(第二,如果不是,我将getYTvideos转换为箭头函数)。