我可以在不使用角度 2+ 中的 cookie 的情况下将 json 对象发送到 restApi 吗?



我正在尝试将 json 类型对象发送到 (angular2+ springMvc + java( Web 项目中的 rest 服务,但这似乎很困难。我也不能使用饼干。

正如我从你的问题中得到的,你正在试图找出一种在 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);
}
);
}
}

现在,您可以根据需要调用这些方法。

希望这有帮助!

祝你好运!!

是的,只要记住设置正确的内容类型标题

constructor(http: HttpClient) {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
this.http.post(<url>, {jsonData}, { headers });
}

最新更新