如果我正确理解您的问题,您希望在 Angular 应用中从后端发送和接收数据。
以角度获取数据:
- 创建服务。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
}
- 创建函数以获取服务中的数据
getConfig() {
return this.http.get(this.configUrl);
}
- 组件内部的调用函数
showConfig() {
this.configService.getConfig()
.subscribe((data: Config) => this.config = {
heroesUrl: data['heroesUrl'],
textfile: data['textfile']
});
}
向服务器发送数据
- 添加标题
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
- 发出 POST 请求
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('addHero', hero))
);
}
- 在表单提交或单击组件内部时调用服务发布方法
this.heroesService
.addHero(newHero)
.subscribe(hero => this.heroes.push(hero));
更多详情,请浏览 angularHttpClient 指南。