我是 Angular 的新手,我曾经使用 PHP 和一些 JavaScript 进行编码。所以看了《英雄之旅》示例代码,还是没有搞清楚HttpClient的概念。假设我要使用 MongoDB 和 Node.js 准备 Web API 服务器。如何准备代码以接受来自英雄之旅示例的 API 请求?有关如何执行此操作的任何示例代码?
同样在英雄之旅示例中, hero.service.ts 中执行大部分 http 进程的部分。
export class HeroService {
private heroesUrl = 'api/heroes'; // URL to web api
这个“api/英雄”指的是哪里?我知道“in-memory-data.service.ts”会处理所有的http请求。但是当我看到里面的代码时,它看起来太简单了。您能否解释一下“in-memory-data.service.ts”如何提供 API 请求所需的数据。例如搜索英雄功能:
searchHeroes(term: string): Observable<Hero[]> {
if (!term.trim()) {
// if not search term, return empty hero array.
return of([]);
}
return this.http.get<Hero[]>(`${this.heroesUrl}/?name=${term}`).pipe(
tap(_ => this.log(`found heroes matching "${term}"`)),
catchError(this.handleError<Hero[]>('searchHeroes', []))
);
}
该函数使用“api/heroes”并提供查询词(英雄名称)并将返回一个英雄数组。我只是不明白为什么 http.get 可以查看 api/heroes 并获取 Hero 数组。api/heroes 和“in-memory-data.service.ts”之间的联系在哪里?谢谢你。