angular - 如何正确订阅发出不同 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;
}
- 提供应用程序会引发错误,因为默认情况下 id 未定义。如何订阅而不出现错误。
- 为什么搜索按钮不起作用?
- 如何仅获取接口中定义的值并丢弃其他所有值?
解决方案
搜索按钮可能有效,但您没有听到结果。
您在 中进行了订阅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);
}
推荐阅读
- batch-file - 创建批处理文件以提示响应并替换文本或 .ini 文件中的文本行
- javascript - ReactJS,反应管理员 3.3.0。错误:在“Connect(withRouter(WithStyles(Layout)))”的上下文中找不到“store”
- java - 指定 packageName 或 assignableTypes 时未应用 Spring @ControllerAdvice
- angular - 如何扭转 mat-progress-spinner 的进度
- android - 为 TextView 设置 FontFamily
- azure - Azure Runbook 问题
- sql-server - 如何访问 XML 的值
- javascript - 如何为特定用户发送浏览器通知?
- nginx - Kubernetes 中的集群内 nginx 代理(sidecar)重写标头
- java - 将 ical4j 添加到 maven jhipster 项目