我正在尝试将json类型的对象发送到(angular2 + springMvc + java)Web项目中的rest服务,但这似乎很困难。我也不能使用cookie。
答案 0 :(得分:1)
从您的问题中得到的答案是,您正在尝试寻找一种在Angular项目中处理http请求的方法。
让我们先看看您的项目结构。您必须具有一个单独的目录,在该目录中,与给定模块相关的所有服务都在其中。
在该目录中,您可以使用ng g s service-name
创建服务,在这种情况下,可以处理http请求。
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {environment} from "../../../../environments/environment";
const BASE_URL = environment.API_PATH;
const WAR = environment.API_WAR;
@Injectable({
providedIn: 'root'
})
export class ServiceNameService {
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
constructor(private http: HttpClient) {
}
getCall() {
return this.http.get(`${BASE_URL}/${WAR}/your/path/all`);
}
getByIdCall(id) {
return this.http.get(`${BASE_URL}/${WAR}/your/path?id=${id}`);
}
deleteByIdCall(id) {
return this.http.delete(`${BASE_URL}/${WAR}/your/path/delete?id=${id}`);
}
postCall(payload: any) {
return this.http.post(`${BASE_URL}/${WAR}/your/path/save`, payload);
}
putCall(id, payload) {
return this.http.put(`${BASE_URL}/${WAR}/your/path/update?id=${id}`, payload);
}
}
现在您必须在组件中调用它,您要执行http请求。
import {Component, OnInit} from '@angular/core';
import {ServiceNameService} from '../../../services/http-services/service-name.service';
@Component({
selector: 'app-config-view',
templateUrl: './config-view.component.html',
styleUrls: ['./config-view.component.scss']
})
export class ConfigViewComponent implements OnInit {
constructor(private serviceNameService: ServiceNameService) {
}
ngOnInit() {
}
loadAll() {
this.serviceNameService.getCall()
.subscribe((data: any) => {
console.log(data);
}, error => {
console.log(error);
}
);
}
loadById(id) {
this.serviceNameService.getByIdCall(id)
.subscribe((data: any) => {
console.log(data);
}, error => {
console.log(error);
}
);
}
deleteById(id) {
this.serviceNameService.deleteByIdCall(id)
.subscribe((data: any) => {
console.log(data);
}, error => {
console.log(error);
}
);
}
save() {
const payload = {
test: "test value"
}
this.serviceNameService.postCall(payload)
.subscribe((data: any) => {
console.log(data);
}, error => {
console.log(error);
}
);
}
update() {
const payload = {
test: "test value updated"
}
this.serviceNameService.putCall(id, payload)
.subscribe((data: any) => {
console.log(data);
}, error => {
console.log(error);
}
);
}
}
现在,您可以根据需要调用这些方法。
希望这会有所帮助!
祝你好运!
答案 1 :(得分:0)
是的,只记得设置正确的内容类型标题
constructor(http: HttpClient) {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
this.http.post(<url>, {jsonData}, { headers });
}