【发布时间】:2019-11-18 14:57:48
【问题描述】:
我正在重写我的 Angular 应用程序,而不是让路由(客户端)从后端 API(Pug、express.js)获取 HTML 模板。 我需要在每次请求访问 API 时在标头中发送 JWT 令牌。我的 API 还支持正文中的令牌。
- 从 API 获取生成的 HTML 的最佳方法是什么? (Fetch vs HttpClient vs AJAX vs ???)
- 如何从概念上将路由转换为从 API 获取?最好的方法是什么?我应该为它写一个服务吗?
- 你能给我一个代码示例吗?
我的尝试:
httpClient: any;
httpOptions = {
// the jwthere below is obviously only a placeholder
headers: new HttpHeaders({ 'authorization': 'jwthere' })
};
constructor(private http: HttpClient) { }
ngOnInit() {
}
fetchDashboard() {
this.http.get('localhost:3000/dashboard').subscribe(j => console.log(j));
}
}
然后在 html 中我将函数定义为:
(click)="fetchDashboard()"
我的尝试不起作用。我可能犯了一些逻辑和设计缺陷。
【问题讨论】:
-
看看Angulars HTTPInterceptor 为每个请求发送一个令牌。
-
@DarrenLamb 它应该与像
httpOptions = { // the jwthere below is obviously only a placeholder headers: new HttpHeaders({ 'authorization': 'jwthere' }) };这样的 HttpClientModule 一起使用,它不需要拦截,因此会增加延迟。这也来自 Angular 文档。 -
@JasonWhite 给我错误
Cannot find name 'RequestOptions'. -
@JasonWhite
"No overload matches this call.\n The last overload gave the following error.\n Argument of type '{ headers: Headers; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: \"body\"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: \"json\"; withCredentials?: boolean; }'.\n Types of property 'headers' are incompatible.\n Type 'Headers' is not assignable to type 'HttpHeaders'... -
“从后端 api 获取 HTML 模板”是什么意思?如果您要加载在服务器上动态生成的 HTML,为什么不回到 10 年前使用 ASP.NET?
标签: angular api fetch httpclient api-design