首页 > 解决方案 > 如何正确订阅发出不同 HTTP 获取请求的服务?[角度]

问题描述

我正在尝试订阅从 API 加载电影数据的服务方法。每当执行搜索时,它都会搜索具有新 ID 的不同电影。如何从组件订阅此内容?

到目前为止我做了什么:

服务:

search(id): Observable<Movie> {
      return this.http.get<Movie>('https://api.themoviedb.org/3/movie/' + id + '?api_key=KeyHidden&language=en-US');
  }

零件:

export class TitleComponent implements OnInit {

  movie: Movie;

  constructor(public ms: MovieService) {}

  ngOnInit() {
    this.ms.search(this.ms.movieid).subscribe(data => this.movie = data);
  }
}

执行搜索的按钮:

<button type="submit" mdbBtn (click)="ms.search(ms.movieid)" id="sub"> Search
        </button>

界面影片:

export interface Movie {
    title: string;
}

  1. 提供应用程序会引发错误,因为默认情况下 id 未定义。如何订阅而不出现错误。
  2. 为什么搜索按钮不起作用?
  3. 如何仅获取接口中定义的值并丢弃其他所有值?

标签: angulartypescriptservicerxjsobservable

解决方案


搜索按钮可能有效,但您没有听到结果。

您在 中进行了订阅ngOnInit,但它本身只获取一次值(带有未定义的 id,这会引发错误)。

您可能想要的是在服务中设置一个可观察对象(实际属性),然后单击按钮而不是调用search,然后在其中将 http 的结果推送到带有.next(value). 这样,组件将收到有关结果的通知。

类似的东西:

电影服务:

private _movie$: BehaviourSubject<Movie> = new BehaviorSubject(null);
movie$ = this.movie$.asObservable();

search(id) {
  this.http.get<Movie>(...).pipe(take(1)).subscribe(data => this.movie$.next(data));
}

标题组件

movie: Movie;

private terminate$: Subject = new Subject();

ngOnInit() {
  this.ms.movie$.pipe(takeUntil(terminate$)).subscribe(data => this.movie = data);
}

ngOnDestroy() {
  terminate$.next();
  terminate$.complete();
}

// You don't really show where the search-id comes from or how it is set, so here I assume it is passed in from the html
onSearch(id) {
  this.ms.search(id);
}

推荐阅读